-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtimer.go
More file actions
53 lines (47 loc) · 1.5 KB
/
Copy pathtimer.go
File metadata and controls
53 lines (47 loc) · 1.5 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
// RaftTimer implements a simple election timeout timer used by the coordinator
// to trigger leader elections when no heartbeat is received within a given
// duration.
package main
import (
"fmt"
"math/rand"
"time"
)
// RaftTimer implements a simple election timeout timer used by the coordinator
// to trigger leader elections when no heartbeat is received within a given
// duration.
type RaftTimer struct {
timeout time.Duration
timeoutSignal chan time.Time
ticker *time.Ticker
}
// NewTimer constructs a RaftTimer with a randomized timeout between 150–300ms.
// The jitter helps avoid simultaneous elections across multiple nodes.
func NewTimer() *RaftTimer {
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
return &RaftTimer{
timeout: time.Duration(r.Float64()*150+150) * time.Millisecond,
timeoutSignal: make(chan time.Time),
}
}
// TimeoutSignal exposes a read-only channel that fires when the election timer
// elapses.
func (t *RaftTimer) TimeoutSignal() <-chan time.Time {
return t.timeoutSignal
}
// StartTimer starts the internal ticker and relays its ticks onto the
// timeoutSignal channel.
func (t *RaftTimer) StartTimer() {
fmt.Println("Election timeout is", t.timeout)
t.ticker = time.NewTicker(t.timeout)
go func() {
for {
t.timeoutSignal <- <-t.ticker.C
}
}()
}
// Reset restarts the timer using the same timeout duration.
func (t *RaftTimer) Reset() {
t.ticker.Reset(t.timeout)
}