timer.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package signal
  2. import (
  3. "context"
  4. "time"
  5. )
  6. type ActivityUpdater interface {
  7. Update()
  8. }
  9. type ActivityTimer struct {
  10. updated chan bool
  11. timeout chan time.Duration
  12. }
  13. func (t *ActivityTimer) Update() {
  14. select {
  15. case t.updated <- true:
  16. default:
  17. }
  18. }
  19. func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
  20. t.timeout <- timeout
  21. }
  22. func (t *ActivityTimer) run(ctx context.Context, cancel context.CancelFunc) {
  23. defer cancel()
  24. timeout := <-t.timeout
  25. if timeout == 0 {
  26. return
  27. }
  28. ticker := time.NewTicker(<-t.timeout)
  29. defer func() {
  30. ticker.Stop()
  31. }()
  32. for {
  33. select {
  34. case <-ticker.C:
  35. case <-ctx.Done():
  36. return
  37. case timeout := <-t.timeout:
  38. if timeout == 0 {
  39. return
  40. }
  41. ticker.Stop()
  42. ticker = time.NewTicker(timeout)
  43. continue
  44. }
  45. select {
  46. case <-t.updated:
  47. // Updated keep waiting.
  48. default:
  49. return
  50. }
  51. }
  52. }
  53. func CancelAfterInactivity(ctx context.Context, cancel context.CancelFunc, timeout time.Duration) *ActivityTimer {
  54. timer := &ActivityTimer{
  55. timeout: make(chan time.Duration, 1),
  56. updated: make(chan bool, 1),
  57. }
  58. timer.timeout <- timeout
  59. go timer.run(ctx, cancel)
  60. return timer
  61. }