-
Notifications
You must be signed in to change notification settings - Fork 6
/
jitter.go
67 lines (56 loc) · 1.12 KB
/
jitter.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
package jitterbug
import (
"time"
)
// Jitter can compute a jitter
type Jitter interface {
// Jitter consumes an interval from a ticker and returns the final, jittered
// duration.
Jitter(time.Duration) time.Duration
}
// Ticker behaves like time.Ticker
type Ticker struct {
C <-chan time.Time
cq chan struct{}
Jitter
Interval time.Duration
}
// New Ticker with the base interval d and the jitter source j.
func New(d time.Duration, j Jitter) (t *Ticker) {
c := make(chan time.Time)
t = &Ticker{
C: c,
cq: make(chan struct{}),
Interval: d,
Jitter: j,
}
go t.loop(c)
return
}
// Stop the Ticker
func (t *Ticker) Stop() { close(t.cq) }
func (t *Ticker) loop(c chan<- time.Time) {
defer close(c)
for {
time.Sleep(t.calcDelay())
select {
case <-t.cq:
return
case c <- time.Now():
default: // there may be nobody ready to recv
}
}
}
func (t *Ticker) calcDelay() time.Duration { return t.Jitter.Jitter(t.Interval) }
func min(a, b time.Duration) time.Duration {
if a > b {
return b
}
return a
}
func max(a, b time.Duration) time.Duration {
if a > b {
return a
}
return b
}