timer.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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, timeout time.Duration) (context.Context, *ActivityTimer) {
  48. ctx, cancel := context.WithCancel(ctx)
  49. timer := &ActivityTimer{
  50. ctx: ctx,
  51. cancel: cancel,
  52. timeout: make(chan time.Duration, 1),
  53. updated: make(chan bool, 1),
  54. }
  55. timer.timeout <- timeout
  56. go timer.run()
  57. return ctx, timer
  58. }