timer.go 701 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. time.Sleep(t.timeout)
  21. select {
  22. case <-t.ctx.Done():
  23. return
  24. case <-t.updated:
  25. default:
  26. t.cancel()
  27. return
  28. }
  29. }
  30. }
  31. func CancelAfterInactivity(ctx context.Context, cancel context.CancelFunc, timeout time.Duration) *ActivityTimer {
  32. timer := &ActivityTimer{
  33. ctx: ctx,
  34. cancel: cancel,
  35. timeout: timeout,
  36. updated: make(chan bool, 1),
  37. }
  38. go timer.run()
  39. return timer
  40. }