-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrol_timer.go
More file actions
69 lines (59 loc) · 1.42 KB
/
control_timer.go
File metadata and controls
69 lines (59 loc) · 1.42 KB
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
package common
import (
"math/rand"
"time"
)
type timerFactory func() <-chan time.Time
type ControlTimer struct {
timerFactory timerFactory
TickCh chan struct{} //sends a signal to listening process
ResetCh chan struct{} //receives instruction to reset the heartbeatTimer
StopCh chan struct{} //receives instruction to stop the heartbeatTimer
ShutdownCh chan struct{} //receives instruction to exit Run loop
Set bool
}
func NewControlTimer(timerFactory timerFactory) *ControlTimer {
return &ControlTimer{
timerFactory: timerFactory,
TickCh: make(chan struct{}),
ResetCh: make(chan struct{}),
StopCh: make(chan struct{}),
ShutdownCh: make(chan struct{}),
}
}
func NewRandomControlTimer(base time.Duration) *ControlTimer {
randomTimeout := func() <-chan time.Time {
minVal := base
if minVal == 0 {
return nil
}
extra := (time.Duration(rand.Int63()) % minVal)
return time.After(minVal + extra)
}
return NewControlTimer(randomTimeout)
}
func (c *ControlTimer) Run() {
setTimer := func() <-chan time.Time {
c.Set = true
return c.timerFactory()
}
timer := setTimer()
for {
select {
case <-timer:
c.TickCh <- struct{}{}
c.Set = false
case <-c.ResetCh:
timer = setTimer()
case <-c.StopCh:
timer = nil
c.Set = false
case <-c.ShutdownCh:
c.Set = false
return
}
}
}
func (c *ControlTimer) Shutdown() {
close(c.ShutdownCh)
}