retry

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 23, 2021 License: Apache-2.0 Imports: 5 Imported by: 7

README

retry

GoDoc

Retry Library for Go

// Retry six times with a maximum backoff of 5 seconds
// between the retry attempts. The maximum backoff is
// reached within the third attempt, since retry uses
// exponential backoff.
var err error
retry.X(6, 5*time.Second, func() bool {
    err = DoSomething()
    return err != nil
})
if err != nil {
	// The error is not nil, so all retries failed.
} else {
	// The error is nil, so one succeeded.
}

Documentation

Overview

Package retry retries something X number of times, with an exponential backoff between each attempt. The backoff is calculated to reach the maximum backoff within three attempts.

Example:

// Retry six times with a maximum backoff of 5 seconds
// between the retry attempts.

var err error
retry.X(6, 5*time.Second, func() bool {
    err = DoSomething()
    return err != nil
})
if err != nil {
    // The error is not nil, so all retries failed.
} else {
    // The error is nil, so one succeeded.
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func X

func X(x int, maxBackoff time.Duration, f func() bool)

X number of retries. Function f should return false if it wants to stop trying, but never more than x+1 calls of f are done. Calls to f have a sleep duration between them.

Example 1:

var err error
retry.X(3, 5*time.Second, func() bool {
    err = DoSomething()
    return err != nil
})

The use of "return err != nil" is an ideomatic way of returning true, keep trying, when the error is not nil.

func XWithContext

func XWithContext(ctx context.Context, x int, maxBackoff time.Duration, f func(ctx context.Context) error) error

XWithContext runs function f until f returns nil or the number of retries exceeds x. Never more than x+1 calls of f are done. Calls to f have a sleep duration between them. XWithContext will return a wrapped error around f's errors if all attempts fail. The attempts can be cancelled with ctx. If f does not cancel when ctx is done, then the currently-running f will be allowed to complete first.

Example 1:

retry.XWithContext(ctx, 3, 5*time.Second, func(ctx context.Context) error {
    err := DoSomething(ctx)
    return err
})

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL