timer.go 1.1 KB

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