-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathelection_timer.go
More file actions
101 lines (85 loc) · 1.79 KB
/
election_timer.go
File metadata and controls
101 lines (85 loc) · 1.79 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
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
package graft
import (
"time"
)
type Electable interface {
StartElection()
}
type Tickable interface {
Stop()
Chan() <-chan time.Time
}
type ElectionTimer struct {
electable Electable
ElectionChannel chan int
shutDownChannel chan int
resets int
duration time.Duration
tickerBuilder func(time.Duration) Tickable
stopTickerChan chan int
}
type WrappedTicker struct {
ticker *time.Ticker
}
func (ticker WrappedTicker) Chan() <-chan time.Time {
return ticker.ticker.C
}
func (ticker WrappedTicker) Stop() {
ticker.ticker.Stop()
}
func DefaultTicker(d time.Duration) Tickable {
return &WrappedTicker{
ticker: time.NewTicker(d),
}
}
func NewElectionTimer(duration time.Duration, electable Electable) *ElectionTimer {
timer := &ElectionTimer{
electable: electable,
ElectionChannel: make(chan int),
shutDownChannel: make(chan int),
duration: duration,
tickerBuilder: DefaultTicker,
}
go timer.waitForElection()
return timer
}
func (timer *ElectionTimer) Reset() {
timer.stopTimer()
timer.StartTimer()
}
func (timer *ElectionTimer) StartTimer() {
timer.stopTickerChan = make(chan int)
go func(ticker Tickable) {
for {
select {
case <-ticker.Chan():
timer.ElectionChannel <- 1
case <-timer.stopTickerChan:
ticker.Stop()
return
}
}
}(timer.tickerBuilder(timer.duration))
}
func (timer *ElectionTimer) ShutDown() {
timer.stopTimer()
timer.shutDownChannel <- 1
}
func (timer *ElectionTimer) startElection() {
timer.electable.StartElection()
}
func (timer *ElectionTimer) stopTimer() {
if timer.stopTickerChan != nil {
timer.stopTickerChan <- 1
}
}
func (timer *ElectionTimer) waitForElection() {
for {
select {
case <-timer.ElectionChannel:
timer.startElection()
case <-timer.shutDownChannel:
return
}
}
}