-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathticker.go
64 lines (58 loc) · 1.42 KB
/
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
package clock
import (
"math/rand"
"time"
)
// RandomTicker is similar to time.Ticker but ticks at random intervals between
// the min and max duration values (stored internally as int64 nanosecond
// counts).
type RandomTicker struct {
C chan time.Time
stopc chan chan struct{}
min int64
max int64
}
// NewRandomTicker returns a pointer to an initialized instance of the
// RandomTicker. Min and max are durations of the shortest and longest allowed
// ticks. Ticker will run in a goroutine until explicitly stopped.
func NewRandomTicker(min, max time.Duration) *RandomTicker {
rt := &RandomTicker{
C: make(chan time.Time),
stopc: make(chan chan struct{}),
min: min.Nanoseconds(),
max: max.Nanoseconds(),
}
go rt.loop()
return rt
}
// Stop terminates the ticker goroutine and closes the C channel.
func (rt *RandomTicker) Stop() {
c := make(chan struct{})
rt.stopc <- c
<-c
}
func (rt *RandomTicker) loop() {
defer close(rt.C)
t := time.NewTimer(rt.nextInterval())
for {
// either a stop signal or a timeout
select {
case c := <-rt.stopc:
t.Stop()
close(c)
return
case <-t.C:
select {
case rt.C <- time.Now():
t.Stop()
t = time.NewTimer(rt.nextInterval())
default:
// there could be noone receiving...
}
}
}
}
func (rt *RandomTicker) nextInterval() time.Duration {
interval := rand.Int63n(rt.max-rt.min) + rt.min
return time.Duration(interval) * time.Nanosecond
}