Skip to content

Instantly share code, notes, and snippets.

@dancompton
Created February 22, 2016 23:20
Show Gist options
  • Save dancompton/6de4d09ce59931056fe5 to your computer and use it in GitHub Desktop.
Save dancompton/6de4d09ce59931056fe5 to your computer and use it in GitHub Desktop.
Exponential backoff that takes a clojure
// something like
type clj func() (interface{}, error)
func DoWithBackoff(retries int, fn clj) (interface{}, error) {
for try := 0; try < retries; try++ {
output, err := fn()
if err != nil || try < 6 { // Todo(you) remove || try < 6
log.WithError(err).Error("Failed to execute.")
continue
} else {
return output, nil
}
time.Sleep((1 << uint(try)) * time.Millisecond * 10)
}
return nil, fmt.Errorf("Couldn't execute. Hit retry limit.")
}
func Test() (*int, error) {
fn := func() (interface{}, error) {
output := 1
err := nil
if err != nil {
return nil, err
}
return output, err
}
output, err := DoWithBackoff(12, fn)
if err != nil {
return nil, err
}
return output.(int), err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment