github.com/vmg/backoff@v1.0.0/backoff.go (about) 1 // Package backoff implements backoff algorithms for retrying operations. 2 // 3 // Also has a Retry() helper for retrying operations that may fail. 4 package backoff 5 6 import "time" 7 8 // BackOff is a backoff policy for retrying an operation. 9 type BackOff interface { 10 // NextBackOff returns the duration to wait before retrying the operation, 11 // or backoff.Stop to indicate that no more retries should be made. 12 // 13 // Example usage: 14 // 15 // duration := backoff.NextBackOff(); 16 // if (duration == backoff.Stop) { 17 // // Do not retry operation. 18 // } else { 19 // // Sleep for duration and retry operation. 20 // } 21 // 22 NextBackOff() time.Duration 23 24 // Reset to initial state. 25 Reset() 26 } 27 28 // Indicates that no more retries should be made for use in NextBackOff(). 29 const Stop time.Duration = -1 30 31 // ZeroBackOff is a fixed backoff policy whose backoff time is always zero, 32 // meaning that the operation is retried immediately without waiting, indefinitely. 33 type ZeroBackOff struct{} 34 35 func (b *ZeroBackOff) Reset() {} 36 37 func (b *ZeroBackOff) NextBackOff() time.Duration { return 0 } 38 39 // StopBackOff is a fixed backoff policy that always returns backoff.Stop for 40 // NextBackOff(), meaning that the operation should never be retried. 41 type StopBackOff struct{} 42 43 func (b *StopBackOff) Reset() {} 44 45 func (b *StopBackOff) NextBackOff() time.Duration { return Stop } 46 47 // ConstantBackOff is a backoff policy that always returns the same backoff delay. 48 // This is in contrast to an exponential backoff policy, 49 // which returns a delay that grows longer as you call NextBackOff() over and over again. 50 type ConstantBackOff struct { 51 Interval time.Duration 52 } 53 54 func (b *ConstantBackOff) Reset() {} 55 func (b *ConstantBackOff) NextBackOff() time.Duration { return b.Interval } 56 57 func NewConstantBackOff(d time.Duration) *ConstantBackOff { 58 return &ConstantBackOff{Interval: d} 59 }