From 49c23d036f505d5f73af1233515ad84a90797a53 Mon Sep 17 00:00:00 2001 From: Dan Root Date: Thu, 24 May 2018 14:25:21 -0700 Subject: [PATCH] Switch to using time.Duration for better flexibility. Allows sub-millisecond delays and use of returns from time package functions like time.Until() to create delays. Update README accordingly. --- README.md | 4 ++-- retry.go | 22 +++++++++++----------- retry_test.go | 28 ++++++++++++++-------------- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index a3fcdc1..9190705 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Retrier objects are intended to be re-used, which means you define them once and ```go // create a new retrier that will try a maximum of five times, with // an initial delay of 100 ms and a maximum delay of 1 second -retrier := retry.NewRetrier(5, 100, 1000) +retrier := retry.NewRetrier(5, 100 * time.Millisecond, time.Second) err := retrier.Run(func() error { resp, err := http.Get("http://golang.org") @@ -41,7 +41,7 @@ if err != nil { ```go // create a new retrier that will try a maximum of five times, with // an initial delay of 100 ms and a maximum delay of 1 second -retrier := retry.NewRetrier(5, 100, 1000) +retrier := retry.NewRetrier(5, 100 * time.Millisecond, time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) defer cancel() diff --git a/retry.go b/retry.go index 04110ef..c40ea24 100644 --- a/retry.go +++ b/retry.go @@ -9,9 +9,9 @@ import ( // Default backoff const ( - DefaultMaxTries = 5 - DefaultInitialDelayMS = 200 - DefaultMaxDelayMS = 1000 + DefaultMaxTries = 5 + DefaultInitialDelay = time.Millisecond * 200 + DefaultMaxDelay = time.Millisecond * 1000 ) // Retrier retries code blocks with or without context using an exponential @@ -19,21 +19,21 @@ const ( // which means it is safe to create and use concurrently. type Retrier struct { maxTries int - initialDelay int - maxDelay int + initialDelay time.Duration + maxDelay time.Duration } // NewRetrier returns a retrier for retrying functions with expoential backoff. // If any of the values are <= 0, they will be set to their respective defaults. -func NewRetrier(maxTries, initialDelay, maxDelay int) *Retrier { +func NewRetrier(maxTries int, initialDelay, maxDelay time.Duration) *Retrier { if maxTries <= 0 { maxTries = DefaultMaxTries } if initialDelay <= 0 { - initialDelay = DefaultInitialDelayMS + initialDelay = DefaultInitialDelay } if maxDelay <= 0 { - maxDelay = DefaultMaxDelayMS + maxDelay = DefaultMaxDelay } return &Retrier{maxTries, initialDelay, maxDelay} } @@ -122,10 +122,10 @@ func (t terminalError) Error() string { return t.e.Error() } -func getnextBackoff(attempts, initialDelay, maxDelay int) time.Duration { +func getnextBackoff(attempts int, initialDelay, maxDelay time.Duration) time.Duration { return min( - time.Duration(maxDelay)*time.Millisecond, - time.Duration(randInt63n(int64(initialDelay)*(1<