timer.go 1.0 KB

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