Skip to content

Commit

Permalink
respect ctx in strategy sleeps
Browse files Browse the repository at this point in the history
  • Loading branch information
umputun committed Jan 28, 2019
1 parent c065073 commit 661f286
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 5 deletions.
7 changes: 5 additions & 2 deletions repeater_test.go
Expand Up @@ -22,10 +22,11 @@ func TestRepeatFixed(t *testing.T) {
return e
}

err := NewDefault(10, time.Millisecond).Do(context.Background(), fun)
st := time.Now()
err := NewDefault(10, time.Millisecond*10).Do(context.Background(), fun)
assert.Nil(t, err, "should be ok")
assert.Equal(t, 5, called, "called 5 times")

assert.True(t, time.Since(st) >= 40*time.Millisecond)
called = 0
err = NewDefault(4, time.Millisecond).Do(context.Background(), fun)
assert.NotNil(t, err, "should be err")
Expand Down Expand Up @@ -76,9 +77,11 @@ func TestRepeatFixedCanceled(t *testing.T) {
return errors.New("some error")
}

st := time.Now()
err := NewDefault(10, time.Millisecond*50).Do(ctx, fun)
assert.EqualError(t, err, "some error")
assert.Equal(t, 2, called)
assert.True(t, time.Since(st) >= time.Millisecond*60 && time.Since(st) < time.Millisecond*70)
}

func TestRepeatFixedCriticalError(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion strategy/backoff.go
Expand Up @@ -47,7 +47,7 @@ func (b *Backoff) Start(ctx context.Context) (ch chan struct{}) {
if b.jitter {
delay = rnd.Float64()*(float64(2*minDelay)) + (delay - float64(minDelay))
}
time.Sleep(time.Duration(delay))
sleep(ctx, time.Duration(delay))
}
}
}()
Expand Down
2 changes: 1 addition & 1 deletion strategy/fixed.go
Expand Up @@ -33,7 +33,7 @@ func (s *FixedDelay) Start(ctx context.Context) (ch chan struct{}) {
return
default:
ch <- struct{}{}
time.Sleep(s.delay)
sleep(ctx, s.delay)
}
}
}()
Expand Down
14 changes: 13 additions & 1 deletion strategy/strategy.go
Expand Up @@ -2,7 +2,10 @@
// Strategy result is a channel acting like time.Timer ot time.Tick
package strategy

import "context"
import (
"context"
"time"
)

// Interface for repeater strategy. Returns channel with ticks
type Interface interface {
Expand All @@ -26,3 +29,12 @@ func (s *Once) Start(ctx context.Context) (ch chan struct{}) {
}()
return ch
}

func sleep(ctx context.Context, duration time.Duration) {
select {
case <-time.After(duration):
return
case <-ctx.Done():
return
}
}

0 comments on commit 661f286

Please sign in to comment.