-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
backoff_ticker.go
103 lines (85 loc) · 1.93 KB
/
backoff_ticker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package utils
import (
"sync"
"time"
"github.com/jpillora/backoff"
)
type timerFactory func(d time.Duration) *time.Timer
func newBackoffTicker(tf timerFactory, min, max time.Duration) BackoffTicker {
c := make(chan time.Time, 1)
return BackoffTicker{
createTimer: tf,
b: backoff.Backoff{
Min: min,
Max: max,
},
C: c,
chStop: make(chan struct{}),
}
}
// BackoffTicker sends ticks with periods that increase over time, over a configured range.
type BackoffTicker struct {
createTimer timerFactory
b backoff.Backoff
timer *time.Timer
C chan time.Time
chStop chan struct{}
isRunning bool
sync.Mutex
}
// NewBackoffTicker returns a new BackoffTicker for the given range.
func NewBackoffTicker(min, max time.Duration) BackoffTicker {
return newBackoffTicker(time.NewTimer, min, max)
}
// Start - Starts the ticker
// Returns true if the ticker was not running yet
func (t *BackoffTicker) Start() bool {
t.Lock()
defer t.Unlock()
if t.isRunning {
return false
}
// Reset the backoff
t.b.Reset()
go t.run()
t.isRunning = true
return true
}
// Stop stops the ticker. A ticker can be restarted by calling Start on a
// stopped ticker.
// Returns true if the ticker was actually stopped at this invocation (was previously running)
func (t *BackoffTicker) Stop() bool {
t.Lock()
defer t.Unlock()
if !t.isRunning {
return false
}
t.chStop <- struct{}{}
t.timer = nil
t.isRunning = false
return true
}
func (t *BackoffTicker) run() {
d := t.b.Duration()
for {
// Set up initial tick
if t.timer == nil {
t.timer = t.createTimer(d)
}
select {
case tickTime := <-t.timer.C:
t.C <- tickTime
t.timer.Reset(t.b.Duration())
continue
case <-t.chStop:
return
}
}
}
// Ticks returns the underlying channel.
func (t *BackoffTicker) Ticks() <-chan time.Time {
return t.C
}
func (t *BackoffTicker) Bounds() (time.Duration, time.Duration) {
return t.b.Min, t.b.Max
}