Skip to content

Commit 9710811

Browse files
committed
Added convenience functions for typical types of backoff
1 parent b9d5874 commit 9710811

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

retry.go

+15
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,21 @@ func (c *ExponentialBackoff) Backoff(attempt int) time.Duration {
208208
return time.Duration(backoff)
209209
}
210210

211+
// NoBackoff returns a Backoffer with zero backoff, and zero delay between retries.
212+
func NoBackoff() *ExponentialBackoff {
213+
return &ExponentialBackoff{}
214+
}
215+
216+
// ConstantBackoff returns a Backoffer with a fixed, constant delay between retries and no jitter.
217+
func ConstantBackoff(delay time.Duration) *ExponentialBackoff {
218+
return &ExponentialBackoff{BaseDelay: delay}
219+
}
220+
221+
// ConstantBackoffWithJitter returns a Backoffer with a fixed, constant delay between retries with 20% jitter.
222+
func ConstantBackoffWithJitter(delay time.Duration) *ExponentialBackoff {
223+
return &ExponentialBackoff{BaseDelay: delay, Jitter: 0.2}
224+
}
225+
211226
// Retry retries the http request under certain conditions. The number of retries,
212227
// retry conditions, and the time to sleep between retries can be configured. If
213228
// config is nil, the DefaultRetryConfig will be used.

retry_test.go

+5-10
Original file line numberDiff line numberDiff line change
@@ -107,22 +107,17 @@ func TestExponentialBackoff_Backoff(t *testing.T) {
107107
},
108108
{
109109
name: "no delay",
110-
backoff: ExponentialBackoff{},
110+
backoff: *NoBackoff(),
111111
expected: [5]time.Duration{0, 0, 0, 0, 0},
112112
},
113113
{
114-
name: "fixed delay",
115-
backoff: ExponentialBackoff{
116-
BaseDelay: time.Second,
117-
},
114+
name: "constant delay",
115+
backoff: *ConstantBackoff(time.Second),
118116
expected: [5]time.Duration{time.Second, time.Second, time.Second, time.Second, time.Second},
119117
},
120118
{
121-
name: "fixed delay with jitter",
122-
backoff: ExponentialBackoff{
123-
BaseDelay: time.Second,
124-
Jitter: .2,
125-
},
119+
name: "constant delay with jitter",
120+
backoff: *ConstantBackoffWithJitter(time.Second),
126121
expected: [5]time.Duration{time.Second, time.Second, time.Second, time.Second, time.Second},
127122
expectedJitter: 0.2,
128123
},

0 commit comments

Comments
 (0)