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.

66 lines
1.1 KiB

11 years ago
11 years ago
  1. package common
  2. import "time"
  3. import "sync"
  4. /*
  5. RepeatTimer repeatedly sends a struct{}{} to .Ch after each "dur" period.
  6. It's good for keeping connections alive.
  7. */
  8. type RepeatTimer struct {
  9. Ch chan time.Time
  10. mtx sync.Mutex
  11. name string
  12. ticker *time.Ticker
  13. quit chan struct{}
  14. dur time.Duration
  15. }
  16. func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer {
  17. var t = &RepeatTimer{
  18. Ch: make(chan time.Time),
  19. ticker: time.NewTicker(dur),
  20. quit: make(chan struct{}),
  21. name: name,
  22. dur: dur,
  23. }
  24. go t.fireRoutine(t.ticker)
  25. return t
  26. }
  27. func (t *RepeatTimer) fireRoutine(ticker *time.Ticker) {
  28. for {
  29. select {
  30. case t_ := <-ticker.C:
  31. t.Ch <- t_
  32. case <-t.quit:
  33. return
  34. }
  35. }
  36. }
  37. // Wait the duration again before firing.
  38. func (t *RepeatTimer) Reset() {
  39. t.Stop()
  40. t.mtx.Lock() // Lock
  41. defer t.mtx.Unlock()
  42. t.ticker = time.NewTicker(t.dur)
  43. t.quit = make(chan struct{})
  44. go t.fireRoutine(t.ticker)
  45. }
  46. func (t *RepeatTimer) Stop() bool {
  47. t.mtx.Lock() // Lock
  48. defer t.mtx.Unlock()
  49. exists := t.ticker != nil
  50. if exists {
  51. t.ticker.Stop()
  52. t.ticker = nil
  53. close(t.quit)
  54. }
  55. return exists
  56. }