Skip to content

Commit

Permalink
Merge pull request #28 from lebauce/max-delay
Browse files Browse the repository at this point in the history
Add a MaxDelay option
  • Loading branch information
JaSei authored Feb 25, 2020
2 parents adee513 + be36733 commit 01ec765
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
9 changes: 9 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type DelayTypeFunc func(n uint, config *Config) time.Duration
type Config struct {
attempts uint
delay time.Duration
maxDelay time.Duration
maxJitter time.Duration
onRetry OnRetryFunc
retryIf RetryIfFunc
Expand Down Expand Up @@ -51,6 +52,14 @@ func Delay(delay time.Duration) Option {
}
}

// MaxDelay set maximum delay between retry
// does not apply by default
func MaxDelay(maxDelay time.Duration) Option {
return func(c *Config) {
c.maxDelay = maxDelay
}
}

// MaxJitter sets the maximum random Jitter between retries for RandomDelay
func MaxJitter(maxJitter time.Duration) Option {
return func(c *Config) {
Expand Down
3 changes: 3 additions & 0 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {
}

delayTime := config.delayType(n, config)
if config.maxDelay > 0 && delayTime > config.maxDelay {
delayTime = config.maxDelay
}
time.Sleep(delayTime)
} else {
return nil
Expand Down
16 changes: 15 additions & 1 deletion retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,24 @@ func TestRandomDelay(t *testing.T) {
func() error { return errors.New("test") },
Attempts(3),
DelayType(RandomDelay),
MaxJitter(50 * time.Millisecond),
MaxJitter(50*time.Millisecond),
)
dur := time.Since(start)
assert.Error(t, err)
assert.True(t, dur > 2*time.Millisecond, "3 times random retry is longer then 2ms")
assert.True(t, dur < 100*time.Millisecond, "3 times random retry is shorter then 100ms")
}

func TestMaxDelay(t *testing.T) {
start := time.Now()
err := Do(
func() error { return errors.New("test") },
Attempts(5),
Delay(10*time.Millisecond),
MaxDelay(50*time.Millisecond),
)
dur := time.Since(start)
assert.Error(t, err)
assert.True(t, dur > 170*time.Millisecond, "5 times with maximum delay retry is longer than 70ms")
assert.True(t, dur < 200*time.Millisecond, "5 times with maximum delay retry is shorter than 200ms")
}

0 comments on commit 01ec765

Please sign in to comment.