timer.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. ticker := time.NewTicker(<-t.timeout)
  24. defer func() {
  25. ticker.Stop()
  26. }()
  27. for {
  28. select {
  29. case <-ticker.C:
  30. case <-ctx.Done():
  31. return
  32. case timeout := <-t.timeout:
  33. if timeout == 0 {
  34. cancel()
  35. return
  36. }
  37. ticker.Stop()
  38. ticker = time.NewTicker(timeout)
  39. continue
  40. }
  41. select {
  42. case <-t.updated:
  43. // Updated keep waiting.
  44. default:
  45. cancel()
  46. return
  47. }
  48. }
  49. }
  50. func CancelAfterInactivity(ctx context.Context, cancel context.CancelFunc, timeout time.Duration) *ActivityTimer {
  51. timer := &ActivityTimer{
  52. timeout: make(chan time.Duration, 1),
  53. updated: make(chan bool, 1),
  54. }
  55. timer.timeout <- timeout
  56. go timer.run(ctx, cancel)
  57. return timer
  58. }