Skip to content

Instantly share code, notes, and snippets.

@jwreagor
Last active December 9, 2018 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwreagor/adbbad45d9ba302e7e696d76d0243e1e to your computer and use it in GitHub Desktop.
Save jwreagor/adbbad45d9ba302e7e696d76d0243e1e to your computer and use it in GitHub Desktop.
Backoff Reference/Example
package main
import (
"context"
"errors"
"fmt"
"os"
"time"
"github.com/cenkalti/backoff"
)
// NOTE: These are just samples, always test and determine the correct time scale.
const (
allocInitialInterval = 10 * time.Millisecond
allocMaxInterval = 300 * time.Millisecond
allocMaxElapsedTime = 1 * time.Minute
)
func main() {
exp := backoff.NewExponentialBackOff()
exp.InitialInterval = allocInitialInterval
exp.MaxInterval = allocMaxInterval
exp.MaxElapsedTime = allocMaxElapsedTime
endTime := time.Now().Add(60 * time.Second)
retryFunc := func() error {
if time.Now().Before(endTime) {
fmt.Println(time.Now())
return errors.New("screwed up")
}
fmt.Println(time.Now())
return nil
}
err := backoff.Retry(retryFunc, backoff.WithContext(exp, context.Background()))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment