clock.go 719 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. NewTimer(d time.Duration) Timer
  8. NewTicker(d time.Duration) Ticker
  9. }
  10. type realClock struct{}
  11. func NewClock() Clock {
  12. return &realClock{}
  13. }
  14. func (clock *realClock) Now() time.Time {
  15. return time.Now()
  16. }
  17. func (clock *realClock) Since(t time.Time) time.Duration {
  18. return time.Now().Sub(t)
  19. }
  20. func (clock *realClock) Sleep(d time.Duration) {
  21. <-clock.NewTimer(d).C()
  22. }
  23. func (clock *realClock) NewTimer(d time.Duration) Timer {
  24. return &realTimer{
  25. t: time.NewTimer(d),
  26. }
  27. }
  28. func (clock *realClock) NewTicker(d time.Duration) Ticker {
  29. return &realTicker{
  30. t: time.NewTicker(d),
  31. }
  32. }