Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ func init() {
// capture the most common use cases.
type Strategy func(nth int) time.Duration

// Fibonacci creates a Strategy that returns fib(n) units, where
// fib is the fibonacci function, f(n) = f(n-1) + f(n-2).
func Fibonacci(units time.Duration) Strategy {
return func(n int) time.Duration {
f := [...]time.Duration{1,0}
if n <= 0 {
return 0
}
for i := 1; i < n; i++ {
f[0], f[1] = f[0] + f[1], f[0]
}
return f[0] * units
}
}

// Exponential creates an exponential backoff Strategy that returns
// 2ⁿ units. The values returned by Exponential will increase up to
// the maximum value of time.Duration and will not overflow.
Expand Down
30 changes: 22 additions & 8 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,30 @@ func TestExponentialBackoff(t *testing.T) {
}
}

func TestFibonacciBackoff(t *testing.T) {
ans := []time.Duration{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}
backoff := Fibonacci(1)
for i, v := range ans {
if x := backoff(i); x != v {
t.Errorf("fibonacci backoff(%d) = %s, should be %s", i, x, v)
} else {
t.Logf("fibonacci backoff(%d) = %s", i, x)
}
}
if backoff(-1) != 0 {
t.Errorf("fibonacci backoff(-1) = %s, should be 0ns", backoff(-1))
}
}

func TestIntervalBackoff(t *testing.T) {
x := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
const jitter = 50
backoff := Seconds(x...)
ans := []time.Duration{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
backoff := Intervals(ans...)

for i, v := range x {
t.Logf("fixed backoff(%d) = %s", i, backoff(i))
if backoff(i) != time.Duration(v)*time.Second {
t.Errorf("fixed backoff(%d) = %s, should be > %s", i, backoff(i),
time.Duration(v)*time.Second)
for i, v := range ans {
if x := backoff(i); x != v {
t.Errorf("fixed backoff(%d) = %s, should be %s", i, x, v)
} else {
t.Logf("fixed backoff(%d) = %s", i, x)
}
}
}