backoff.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Package backoff implements backoff algorithms for retrying operations.
  2. //
  3. // Use Retry function for retrying operations that may fail.
  4. // If Retry does not meet your needs,
  5. // copy/paste the function into your project and modify as you wish.
  6. //
  7. // There is also Ticker type similar to time.Ticker.
  8. // You can use it if you need to work with channels.
  9. //
  10. // See Examples section below for usage examples.
  11. package backoff
  12. import "time"
  13. // BackOff is a backoff policy for retrying an operation.
  14. type BackOff interface {
  15. // NextBackOff returns the duration to wait before retrying the operation,
  16. // or backoff. Stop to indicate that no more retries should be made.
  17. //
  18. // Example usage:
  19. //
  20. // duration := backoff.NextBackOff();
  21. // if (duration == backoff.Stop) {
  22. // // Do not retry operation.
  23. // } else {
  24. // // Sleep for duration and retry operation.
  25. // }
  26. //
  27. NextBackOff() time.Duration
  28. // Reset to initial state.
  29. Reset()
  30. }
  31. // Stop indicates that no more retries should be made for use in NextBackOff().
  32. const Stop time.Duration = -1
  33. // ZeroBackOff is a fixed backoff policy whose backoff time is always zero,
  34. // meaning that the operation is retried immediately without waiting, indefinitely.
  35. type ZeroBackOff struct{}
  36. func (b *ZeroBackOff) Reset() {}
  37. func (b *ZeroBackOff) NextBackOff() time.Duration { return 0 }
  38. // StopBackOff is a fixed backoff policy that always returns backoff.Stop for
  39. // NextBackOff(), meaning that the operation should never be retried.
  40. type StopBackOff struct{}
  41. func (b *StopBackOff) Reset() {}
  42. func (b *StopBackOff) NextBackOff() time.Duration { return Stop }
  43. // ConstantBackOff is a backoff policy that always returns the same backoff delay.
  44. // This is in contrast to an exponential backoff policy,
  45. // which returns a delay that grows longer as you call NextBackOff() over and over again.
  46. type ConstantBackOff struct {
  47. Interval time.Duration
  48. }
  49. func (b *ConstantBackOff) Reset() {}
  50. func (b *ConstantBackOff) NextBackOff() time.Duration { return b.Interval }
  51. func NewConstantBackOff(d time.Duration) *ConstantBackOff {
  52. return &ConstantBackOff{Interval: d}
  53. }