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.

65 lines
1.1 KiB

10 years ago
10 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.mtx.Lock() // Lock
  40. defer t.mtx.Unlock()
  41. if t.ticker != nil {
  42. t.ticker.Stop()
  43. }
  44. t.ticker = time.NewTicker(t.dur)
  45. go t.fireRoutine(t.ticker)
  46. }
  47. func (t *RepeatTimer) Stop() bool {
  48. t.mtx.Lock() // Lock
  49. defer t.mtx.Unlock()
  50. exists := t.ticker != nil
  51. if exists {
  52. t.ticker.Stop()
  53. t.ticker = nil
  54. }
  55. return exists
  56. }