Skip to content
Merged
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
20 changes: 12 additions & 8 deletions backoff.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package repeat

import (
"fmt"
"math/rand"
"time"
)
Expand Down Expand Up @@ -128,16 +129,15 @@ func ExponentialBackoffAlgorithm(initialDelay time.Duration, maxDelay time.Durat

return func() time.Duration {
delay := nextDelay
nextDelay = nextDelay * multiplier
if nextDelay < limit {
nextDelay = nextDelay * multiplier
}
if nextDelay > limit {
nextDelay = limit
}

// Fix delay according to jitter.
delta := delay * jitter
delay = delay - delta + (2 * delta * rnd.Float64())

// Fix delay limits.
if delay > limit {
delay = limit
}
delay += delay * jitter * (2*rnd.Float64() - 1)

return time.Duration(delay)
}
Expand Down Expand Up @@ -207,6 +207,10 @@ func (s *ExponentialBackoffBuilder) WithMultiplier(m float64) *ExponentialBackof
//
// Default value is 0.
func (s *ExponentialBackoffBuilder) WithJitter(j float64) *ExponentialBackoffBuilder {
if j < 0 || j > 1 {
panic(fmt.Sprintf(`repeat: jitter "%f" should in range [0..1]`, j))
}

s.Jitter = j
return s
}
Expand Down
13 changes: 6 additions & 7 deletions backoff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,12 @@ func TestExponentialBackoff(t *testing.T) {
ExponentialBackoff(354 * time.Millisecond).WithJitter(.9).WithMultiplier(1.12).WithMaxDelay(5 * time.Second).Set()(do)

initDelay := float64(354 * time.Millisecond)
for i := 0; i < 30; i++ {
c := math.Pow(1.12, float64(i))
fi := .9 * c
max := time.Duration((c + fi) * initDelay)
if max > 5*time.Second {
max = 5 * time.Second
for i := 0; i < 300; i++ {
c := math.Pow(1.12, float64(i)) * initDelay
if c > float64(5*time.Second) {
c = float64(5 * time.Second)
}
InRange(t, do.Backoff(), time.Duration((c-fi)*initDelay), max)
fi := .9 * c
InRange(t, do.Backoff(), time.Duration(c-fi), time.Duration(c+fi))
}
}