backoff.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //Package backoff helps you at backing off !
  2. //
  3. //It was forked from github.com/cenkalti/backoff which is awesome.
  4. //
  5. //This BackOff sleeps upon BackOff() and calculates its next backoff time instead of returning the duration to sleep.
  6. package backoff
  7. import "time"
  8. // Interface interface to use after a retryable operation failed.
  9. // A Interface.BackOff sleeps.
  10. type Interface interface {
  11. // Example usage:
  12. //
  13. // for ;; {
  14. // err, canRetry := somethingThatCanFail()
  15. // if err != nil && canRetry {
  16. // backoffer.Backoff()
  17. // }
  18. // }
  19. BackOff()
  20. // Reset to initial state.
  21. Reset()
  22. }
  23. // ZeroBackOff is a fixed back-off policy whose back-off time is always zero,
  24. // meaning that the operation is retried immediately without waiting.
  25. type ZeroBackOff struct{}
  26. var _ Interface = (*ZeroBackOff)(nil)
  27. func (b *ZeroBackOff) Reset() {}
  28. func (b *ZeroBackOff) BackOff() {}
  29. type ConstantBackOff struct {
  30. Interval time.Duration
  31. }
  32. var _ Interface = (*ConstantBackOff)(nil)
  33. func (b *ConstantBackOff) Reset() {}
  34. func (b *ConstantBackOff) BackOff() {
  35. time.Sleep(b.Interval)
  36. }
  37. func NewConstant(d time.Duration) *ConstantBackOff {
  38. return &ConstantBackOff{Interval: d}
  39. }