timer.go 750 B

1234567891011121314151617181920212223242526272829303132333435
  1. package backoff
  2. import "time"
  3. type Timer interface {
  4. Start(duration time.Duration)
  5. Stop()
  6. C() <-chan time.Time
  7. }
  8. // defaultTimer implements Timer interface using time.Timer
  9. type defaultTimer struct {
  10. timer *time.Timer
  11. }
  12. // C returns the timers channel which receives the current time when the timer fires.
  13. func (t *defaultTimer) C() <-chan time.Time {
  14. return t.timer.C
  15. }
  16. // Start starts the timer to fire after the given duration
  17. func (t *defaultTimer) Start(duration time.Duration) {
  18. if t.timer == nil {
  19. t.timer = time.NewTimer(duration)
  20. } else {
  21. t.timer.Reset(duration)
  22. }
  23. }
  24. // Stop is called when the timer is not used anymore and resources may be freed.
  25. func (t *defaultTimer) Stop() {
  26. if t.timer != nil {
  27. t.timer.Stop()
  28. }
  29. }