timer.go 821 B

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