timer.go 886 B

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