Involved Source Files Package backoff implements backoff algorithms for retrying operations.
Use Retry function for retrying operations that may fail.
If Retry does not meet your needs,
copy/paste the function into your project and modify as you wish.
There is also Ticker type similar to time.Ticker.
You can use it if you need to work with channels.
See Examples section below for usage examples.context.goexponential.goretry.goticker.gotimer.gotries.go
BackOffContext is a backoff policy that stops retrying after the context
is canceled.( BackOffContext) Context() context.Context NextBackOff returns the duration to wait before retrying the operation,
or backoff. Stop to indicate that no more retries should be made.
Example usage:
duration := backoff.NextBackOff();
if (duration == backoff.Stop) {
// Do not retry operation.
} else {
// Sleep for duration and retry operation.
} Reset to initial state.
*backOffContext
BackOffContext : BackOff
func WithContext(b BackOff, ctx context.Context) BackOffContext
Clock is an interface that returns current time for BackOff.( Clock) Now() time.Time
*github.com/gotd/neo.Time
github.com/gotd/td/clock.Clock(interface)
go.uber.org/zap/zapcore.Clock(interface)systemClock
github.com/gotd/td/clock.systemClock
go.uber.org/zap/zapcore.systemClock
ConstantBackOff is a backoff policy that always returns the same backoff delay.
This is in contrast to an exponential backoff policy,
which returns a delay that grows longer as you call NextBackOff() over and over again.Intervaltime.Duration(*ConstantBackOff) NextBackOff() time.Duration(*ConstantBackOff) Reset()
*ConstantBackOff : BackOff
func NewConstantBackOff(d time.Duration) *ConstantBackOff
ExponentialBackOff is a backoff implementation that increases the backoff
period for each retry attempt using a randomization function that grows exponentially.
NextBackOff() is calculated using the following formula:
randomized interval =
RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor])
In other words NextBackOff() will range between the randomization factor
percentage below and above the retry interval.
For example, given the following parameters:
RetryInterval = 2
RandomizationFactor = 0.5
Multiplier = 2
the actual backoff period used in the next retry attempt will range between 1 and 3 seconds,
multiplied by the exponential, that is, between 2 and 6 seconds.
Note: MaxInterval caps the RetryInterval and not the randomized interval.
If the time elapsed since an ExponentialBackOff instance is created goes past the
MaxElapsedTime, then the method NextBackOff() starts returning backoff.Stop.
The elapsed time can be reset by calling Reset().
Example: Given the following default arguments, for 10 tries the sequence will be,
and assuming we go over the MaxElapsedTime on the 10th try:
Request # RetryInterval (seconds) Randomized Interval (seconds)
1 0.5 [0.25, 0.75]
2 0.75 [0.375, 1.125]
3 1.125 [0.562, 1.687]
4 1.687 [0.8435, 2.53]
5 2.53 [1.265, 3.795]
6 3.795 [1.897, 5.692]
7 5.692 [2.846, 8.538]
8 8.538 [4.269, 12.807]
9 12.807 [6.403, 19.210]
10 19.210 backoff.Stop
Note: Implementation is not thread-safe.ClockClockInitialIntervaltime.Duration After MaxElapsedTime the ExponentialBackOff returns Stop.
It never stops if MaxElapsedTime == 0.MaxIntervaltime.DurationMultiplierfloat64RandomizationFactorfloat64Stoptime.DurationcurrentIntervaltime.DurationstartTimetime.Time GetElapsedTime returns the elapsed time since an ExponentialBackOff instance
is created and is reset when Reset() is called.
The elapsed time is computed using time.Now().UnixNano(). It is
safe to call even while the backoff policy is used by a running
ticker. NextBackOff calculates the next backoff interval using the formula:
Randomized interval = RetryInterval * (1 ± RandomizationFactor) Reset the interval back to the initial retry interval and restarts the timer.
Reset must be called before using b. Increments the current interval by multiplying it with the multiplier.
*ExponentialBackOff : BackOff
func NewExponentialBackOff() *ExponentialBackOff
PermanentError signals that the operation should not be retried.Errerror(*PermanentError) Error() string(*PermanentError) Is(target error) bool(*PermanentError) Unwrap() error
*PermanentError : github.com/go-faster/errors.Wrapper
*PermanentError : error
StopBackOff is a fixed backoff policy that always returns backoff.Stop for
NextBackOff(), meaning that the operation should never be retried.(*StopBackOff) NextBackOff() time.Duration(*StopBackOff) Reset()
*StopBackOff : BackOff
ZeroBackOff is a fixed backoff policy whose backoff time is always zero,
meaning that the operation is retried immediately without waiting, indefinitely.(*ZeroBackOff) NextBackOff() time.Duration(*ZeroBackOff) Reset()
*ZeroBackOff : BackOff
defaultTimer implements Timer interface using time.Timertimer*time.Timer C returns the timers channel which receives the current time when the timer fires. Start starts the timer to fire after the given duration Stop is called when the timer is not used anymore and resources may be freed.
*defaultTimer : Timer
NewExponentialBackOff creates an instance of ExponentialBackOff using default values.
NewTicker returns a new Ticker containing a channel that will send
the time at times specified by the BackOff argument. Ticker is
guaranteed to tick at least once. The channel is closed when Stop
method is called or BackOff stops. It is not safe to manipulate the
provided backoff policy (notably calling NextBackOff or Reset)
while the ticker is running.
NewTickerWithTimer returns a new Ticker with a custom timer.
A default timer that uses system timer is used when nil is passed.
Permanent wraps the given err in a *PermanentError.
Retry the operation o until it does not return error or BackOff stops.
o is guaranteed to be run at least once.
If o returns a *PermanentError, the operation is not retried, and the
wrapped error is returned.
Retry sleeps the goroutine for the duration returned by BackOff after a
failed operation returns.
RetryNotify calls notify function with the error and wait duration
for each failed attempt before sleep.
Type Parameters:
T: any RetryNotifyWithData is like RetryNotify but returns data in the response too.
RetryNotifyWithTimer calls notify function with the error and wait duration using the given Timer
for each failed attempt before sleep.
A default timer that uses system timer is used when nil is passed.
Type Parameters:
T: any RetryNotifyWithTimerAndData is like RetryNotifyWithTimer but returns data in the response too.
Type Parameters:
T: any RetryWithData is like Retry but returns data in the response too.
WithContext returns a BackOffContext with context ctx
ctx must not be nil
WithMaxRetries creates a wrapper around another BackOff, which will
return Stop if NextBackOff() has been called too many times since
the last time Reset() was called
Note: Implementation is not thread-safe.
Returns a random value from the following interval:
[currentInterval - randomizationFactor * currentInterval, currentInterval + randomizationFactor * currentInterval].
Package-Level Variables (only one, which is exported)
SystemClock implements Clock interface that uses time.Now().
Package-Level Constants (total 6, all are exported)
Default values for ExponentialBackOff.
Default values for ExponentialBackOff.
Default values for ExponentialBackOff.
Default values for ExponentialBackOff.
Default values for ExponentialBackOff.
Stop indicates that no more retries should be made for use in NextBackOff().
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.