Skip to content

Commit

Permalink
Added convenience functions for typical types of backoff
Browse files Browse the repository at this point in the history
  • Loading branch information
ansel1 committed Feb 15, 2023
1 parent b9d5874 commit 9710811
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
15 changes: 15 additions & 0 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,21 @@ func (c *ExponentialBackoff) Backoff(attempt int) time.Duration {
return time.Duration(backoff)
}

// NoBackoff returns a Backoffer with zero backoff, and zero delay between retries.
func NoBackoff() *ExponentialBackoff {
return &ExponentialBackoff{}
}

// ConstantBackoff returns a Backoffer with a fixed, constant delay between retries and no jitter.
func ConstantBackoff(delay time.Duration) *ExponentialBackoff {
return &ExponentialBackoff{BaseDelay: delay}
}

// ConstantBackoffWithJitter returns a Backoffer with a fixed, constant delay between retries with 20% jitter.
func ConstantBackoffWithJitter(delay time.Duration) *ExponentialBackoff {
return &ExponentialBackoff{BaseDelay: delay, Jitter: 0.2}
}

// Retry retries the http request under certain conditions. The number of retries,
// retry conditions, and the time to sleep between retries can be configured. If
// config is nil, the DefaultRetryConfig will be used.
Expand Down
15 changes: 5 additions & 10 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,22 +107,17 @@ func TestExponentialBackoff_Backoff(t *testing.T) {
},
{
name: "no delay",
backoff: ExponentialBackoff{},
backoff: *NoBackoff(),
expected: [5]time.Duration{0, 0, 0, 0, 0},
},
{
name: "fixed delay",
backoff: ExponentialBackoff{
BaseDelay: time.Second,
},
name: "constant delay",
backoff: *ConstantBackoff(time.Second),
expected: [5]time.Duration{time.Second, time.Second, time.Second, time.Second, time.Second},
},
{
name: "fixed delay with jitter",
backoff: ExponentialBackoff{
BaseDelay: time.Second,
Jitter: .2,
},
name: "constant delay with jitter",
backoff: *ConstantBackoffWithJitter(time.Second),
expected: [5]time.Duration{time.Second, time.Second, time.Second, time.Second, time.Second},
expectedJitter: 0.2,
},
Expand Down

0 comments on commit 9710811

Please sign in to comment.