For instance, try writing a reusable exponential backoff algorithm […] Oh, and you can’t use interface{}.
How about something like this?
func ExponentialBackoff(tries int, unit time.Duration, f func() error) error { var err error for i := 0; i < tries; i++ { err = f() if err == nil { return nil } top := int32(math.Exp2(float64(i))) + 2 n := rand.Int31n(top) time.Sleep(time.Duration(n) * unit) } return err }
Of course it could be simplified to remove the unit argument if you knew ahead of time which unit you wanted to use.
unit
It could be used like so:
n := 0 f := func() error { if n > 5 { return nil } n++ return errors.New("failed") } ExponentialBackoff(10, time.Millisecond, f)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
How about something like this?
Of course it could be simplified to remove the
unit
argument if you knew ahead of time which unit you wanted to use.It could be used like so: