Skip to content

Commit

Permalink
Prefer time.Timer to time.Sleep when polling (#373)
Browse files Browse the repository at this point in the history
  • Loading branch information
tdmanv committed Oct 23, 2019
1 parent cfc493b commit 47338da
Showing 1 changed file with 12 additions and 24 deletions.
36 changes: 12 additions & 24 deletions pkg/poll/poll.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,7 @@ func Wait(ctx context.Context, f Func) error {
// WaitWithBackoff calls a function until it returns true, an error, or until
// the context is done.
func WaitWithBackoff(ctx context.Context, b backoff.Backoff, f Func) error {
for {
if ok, err := f(ctx); err != nil || ok {
return err
}
select {
case <-ctx.Done():
return errors.WithStack(ctx.Err())
default:
}
sleep := b.Duration()
if deadline, ok := ctx.Deadline(); ok {
ctxSleep := deadline.Sub(time.Now())
sleep = minDuration(sleep, ctxSleep)
}
time.Sleep(sleep)
}
return WaitWithBackoffWithRetries(ctx, b, 0, IsNeverRetryable, f)
}

// WaitWithRetries will invoke a function `f` until it returns true or the
Expand All @@ -88,28 +73,31 @@ func WaitWithBackoffWithRetries(ctx context.Context, b backoff.Backoff, numRetri
return errors.New("numRetries must be non-negative")
}

t := time.NewTimer(0)
<-t.C
retries := 0
for {
ok, err := f(ctx)
if err != nil {
switch {
case err != nil:
if !r(err) || retries >= numRetries {
return err
}
retries++
} else if ok {
case ok:
return nil
}
select {
case <-ctx.Done():
return errors.Wrap(ctx.Err(), "Context done while polling")
default:
}
sleep := b.Duration()
if deadline, ok := ctx.Deadline(); ok {
ctxSleep := deadline.Sub(time.Now())
sleep = minDuration(sleep, ctxSleep)
}
time.Sleep(sleep)
t.Reset(sleep)
select {
case <-ctx.Done():
return errors.Wrap(ctx.Err(), "Context done while polling")
case <-t.C:
}
}
}

Expand Down

0 comments on commit 47338da

Please sign in to comment.