You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
872 B

10 years ago
10 years ago
  1. package common
  2. import "time"
  3. /*
  4. RepeatTimer repeatedly sends a struct{}{} to .Ch after each "dur" period.
  5. It's good for keeping connections alive.
  6. */
  7. type RepeatTimer struct {
  8. Name string
  9. Ch chan struct{}
  10. quit chan struct{}
  11. dur time.Duration
  12. timer *time.Timer
  13. }
  14. func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer {
  15. var ch = make(chan struct{})
  16. var quit = make(chan struct{})
  17. var t = &RepeatTimer{Name: name, Ch: ch, dur: dur, quit: quit}
  18. t.timer = time.AfterFunc(dur, t.fireRoutine)
  19. return t
  20. }
  21. func (t *RepeatTimer) fireRoutine() {
  22. select {
  23. case t.Ch <- struct{}{}:
  24. t.timer.Reset(t.dur)
  25. case <-t.quit:
  26. // do nothing
  27. default:
  28. t.timer.Reset(t.dur)
  29. }
  30. }
  31. // Wait the duration again before firing.
  32. func (t *RepeatTimer) Reset() {
  33. t.timer.Reset(t.dur)
  34. }
  35. func (t *RepeatTimer) Stop() bool {
  36. close(t.quit)
  37. return t.timer.Stop()
  38. }