timer.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package clock
  2. import "time"
  3. type Timer struct {
  4. C <-chan time.Time
  5. timer *time.Timer
  6. fakeTimer *fakeTimer
  7. }
  8. func (t *Timer) Reset(d time.Duration) bool {
  9. if t.timer != nil {
  10. return t.timer.Reset(d)
  11. }
  12. return t.fakeTimer.Reset(d)
  13. }
  14. func (t *Timer) Stop() bool {
  15. if t.timer != nil {
  16. return t.timer.Stop()
  17. }
  18. return t.fakeTimer.Stop()
  19. }
  20. type fakeTimer struct {
  21. // c is the same chan as C in the Timer that contains this fakeTimer
  22. c chan<- time.Time
  23. // clk is kept so we can maintain just one lock and to add and attempt to
  24. // send the times made by this timer during Resets and Stops
  25. clk *fake
  26. // active is true until the fakeTimer's send is attempted or it has been
  27. // stopped
  28. active bool
  29. // sends is where we store all the sends made by this timer so we can
  30. // deactivate the old ones when Reset or Stop is called.
  31. sends []*send
  32. }
  33. func (ft *fakeTimer) Reset(d time.Duration) bool {
  34. ft.clk.Lock()
  35. defer ft.clk.Unlock()
  36. target := ft.clk.t.Add(d)
  37. active := ft.active
  38. ft.active = true
  39. for _, s := range ft.sends {
  40. s.active = false
  41. }
  42. s := ft.clk.addSend(target, ft)
  43. ft.sends = []*send{s}
  44. ft.clk.sendTimes()
  45. return active
  46. }
  47. func (ft *fakeTimer) Stop() bool {
  48. ft.clk.Lock()
  49. defer ft.clk.Unlock()
  50. active := ft.active
  51. ft.active = false
  52. for _, s := range ft.sends {
  53. s.active = false
  54. }
  55. ft.sends = nil
  56. ft.clk.sendTimes()
  57. return active
  58. }