timer.go 964 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package utils
  2. import "time"
  3. // A Timer wrapper that behaves correctly when resetting
  4. type Timer struct {
  5. t *time.Timer
  6. read bool
  7. deadline time.Time
  8. }
  9. // NewTimer creates a new timer that is not set
  10. func NewTimer() *Timer {
  11. return &Timer{t: time.NewTimer(0)}
  12. }
  13. // Chan returns the channel of the wrapped timer
  14. func (t *Timer) Chan() <-chan time.Time {
  15. return t.t.C
  16. }
  17. // Reset the timer, no matter whether the value was read or not
  18. func (t *Timer) Reset(deadline time.Time) {
  19. if deadline.Equal(t.deadline) && !t.read {
  20. // No need to reset the timer
  21. return
  22. }
  23. // We need to drain the timer if the value from its channel was not read yet.
  24. // See https://groups.google.com/forum/#!topic/golang-dev/c9UUfASVPoU
  25. if !t.t.Stop() && !t.read {
  26. <-t.t.C
  27. }
  28. t.t.Reset(time.Until(deadline))
  29. t.read = false
  30. t.deadline = deadline
  31. }
  32. // SetRead should be called after the value from the chan was read
  33. func (t *Timer) SetRead() {
  34. t.read = true
  35. }