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.

40 lines
784 B

11 years ago
11 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. Ch chan struct{}
  9. quit chan struct{}
  10. dur time.Duration
  11. timer *time.Timer
  12. }
  13. func NewRepeatTimer(dur time.Duration) *RepeatTimer {
  14. var ch = make(chan struct{})
  15. var quit = make(chan struct{})
  16. var t = &RepeatTimer{Ch: ch, dur: dur, quit: quit}
  17. t.timer = time.AfterFunc(dur, t.fireRoutine)
  18. return t
  19. }
  20. func (t *RepeatTimer) fireRoutine() {
  21. select {
  22. case t.Ch <- struct{}{}:
  23. t.timer.Reset(t.dur)
  24. case <-t.quit:
  25. }
  26. }
  27. // Wait the duration again before firing.
  28. func (t *RepeatTimer) Reset() {
  29. t.timer.Reset(t.dur)
  30. }
  31. func (t *RepeatTimer) Stop() bool {
  32. close(t.quit)
  33. return t.timer.Stop()
  34. }