linear.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package backoff
  2. // LinearBackOff is a back-off policy whose back-off time is multiplied by mult and incremented by incr
  3. // each time it is called.
  4. // mult can be one ;).
  5. import "time"
  6. // grows linearly until
  7. type LinearBackOff struct {
  8. InitialInterval time.Duration
  9. Multiplier float64
  10. Increment time.Duration
  11. MaxInterval time.Duration
  12. currentInterval time.Duration
  13. }
  14. var _ Interface = (*LinearBackOff)(nil)
  15. func NewLinear(from, to, incr time.Duration, mult float64) *LinearBackOff {
  16. return &LinearBackOff{
  17. InitialInterval: from,
  18. MaxInterval: to,
  19. currentInterval: from,
  20. Increment: incr,
  21. Multiplier: mult,
  22. }
  23. }
  24. func (lb *LinearBackOff) Reset() {
  25. lb.currentInterval = lb.InitialInterval
  26. }
  27. func (lb *LinearBackOff) increment() {
  28. lb.currentInterval = time.Duration(float64(lb.currentInterval) * lb.Multiplier)
  29. lb.currentInterval += lb.Increment
  30. if lb.currentInterval > lb.MaxInterval {
  31. lb.currentInterval = lb.MaxInterval
  32. }
  33. }
  34. func (lb *LinearBackOff) BackOff() {
  35. time.Sleep(lb.currentInterval)
  36. lb.increment()
  37. }