Skip to content

Commit

Permalink
refactor: retry improvements (#72)
Browse files Browse the repository at this point in the history
## Description

Before the retry function was blocking during the default case. If
context was cancelled during the function call that's being retried it
wouldn't continue. Now it will. Code is generally cleaner as well.
  • Loading branch information
AustinAbro321 authored Apr 22, 2024
1 parent 115c415 commit 5cf5b55
Showing 1 changed file with 4 additions and 10 deletions.
14 changes: 4 additions & 10 deletions helpers/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,13 @@ func RetryWithContext(ctx context.Context, fn func() error, attempts int, delay
return errors.New("invalid number of attempts, must be at least 1")
}
var err error
timer := time.NewTimer(0)
defer timer.Stop()
for r := 0; r < attempts; r++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
case <-timer.C:
err = fn()
if err == nil {
return nil
Expand All @@ -53,15 +55,7 @@ func RetryWithContext(ctx context.Context, fn func() error, attempts int, delay

logger("Retrying in %s", backoff)

timer := time.NewTimer(backoff)
select {
case <-timer.C:
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
return ctx.Err()
}
timer.Reset(backoff)
}
}

Expand Down

0 comments on commit 5cf5b55

Please sign in to comment.