clock.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package clock
  2. import "time"
  3. type Clock interface {
  4. Now() time.Time
  5. Sleep(d time.Duration)
  6. Since(t time.Time) time.Duration
  7. // After waits for the duration to elapse and then sends the current time
  8. // on the returned channel.
  9. // It is equivalent to clock.NewTimer(d).C.
  10. // The underlying Timer is not recovered by the garbage collector
  11. // until the timer fires. If efficiency is a concern, use clock.NewTimer
  12. // instead and call Timer.Stop if the timer is no longer needed.
  13. After(d time.Duration) <-chan time.Time
  14. NewTimer(d time.Duration) Timer
  15. NewTicker(d time.Duration) Ticker
  16. }
  17. type realClock struct{}
  18. func NewClock() Clock {
  19. return &realClock{}
  20. }
  21. func (clock *realClock) Now() time.Time {
  22. return time.Now()
  23. }
  24. func (clock *realClock) Since(t time.Time) time.Duration {
  25. return time.Now().Sub(t)
  26. }
  27. func (clock *realClock) Sleep(d time.Duration) {
  28. <-clock.NewTimer(d).C()
  29. }
  30. func (clock *realClock) After(d time.Duration) <-chan time.Time {
  31. return clock.NewTimer(d).C()
  32. }
  33. func (clock *realClock) NewTimer(d time.Duration) Timer {
  34. return &realTimer{
  35. t: time.NewTimer(d),
  36. }
  37. }
  38. func (clock *realClock) NewTicker(d time.Duration) Ticker {
  39. return &realTicker{
  40. t: time.NewTicker(d),
  41. }
  42. }