Skip to content

Commit

Permalink
Add delay and backoff strategies
Browse files Browse the repository at this point in the history
  • Loading branch information
darylnwk committed Mar 12, 2020
1 parent 2a9ea37 commit 83bde1c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
12 changes: 11 additions & 1 deletion backoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ package retry
import "time"

// NoBackoff defines no backoff strategy
func NoBackoff() time.Duration {
func NoBackoff(_ uint, _ time.Duration) time.Duration {
return time.Duration(0)
}

// ConstantBackoff defines constant backoff strategy
func ConstantBackoff(_ uint, delay time.Duration) time.Duration {
return delay
}

// ExponentialBackoff defines exponential backoff strategy
func ExponentialBackoff(n uint, delay time.Duration) time.Duration {
return delay * (1 << n)
}
7 changes: 5 additions & 2 deletions retryer.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ type Retryer struct {

// Backoff defines a backoff function that returns `time.Duration`
// This is applied on subsequent attempts.
Backoff func() time.Duration
Backoff func(n uint, delay time.Duration) time.Duration

// Delay defines duration to delay
Delay time.Duration
}

// Do executes `fn` and returns success if `fn` executed succesfully and any errors that occurred
Expand All @@ -30,7 +33,7 @@ func (retryer Retryer) Do(fn func() error) (bool, Errors) {
for n < retryer.Attempts {
// Backoff after first attempt only
if n > 0 {
time.Sleep(retryer.Backoff())
time.Sleep(retryer.Backoff(n, retryer.Delay))
}

err := fn()
Expand Down
4 changes: 3 additions & 1 deletion retryer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import (
)

func TestRetry_Do_Success(t *testing.T) {
retryer := retry.Retryer{}
retryer := retry.Retryer{
Backoff: retry.ConstantBackoff,
}
ok, err := retryer.Do(func() error {
return nil
})
Expand Down

0 comments on commit 83bde1c

Please sign in to comment.