/
timer_wheel.go
200 lines (172 loc) · 3.98 KB
/
timer_wheel.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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package utils
import (
"errors"
"sync"
"time"
)
type TimerWheel struct {
state int
tickDuration time.Duration
roundDuration time.Duration
wheelCount int
wheel []*Iterator
tick *time.Ticker
lock sync.Mutex
wheelCursor int
mask int
}
type TimerTask interface {
Expire()
}
type Iterator struct {
items map[string]*WheelTimeOut
}
type WheelTimeOut struct {
delay time.Duration
index int
rounds int
task TimerTask
}
const (
default_tick_duration = time.Second
default_wheel_count = 3600
)
func NewTimerWheel() *TimerWheel {
return &TimerWheel{
tickDuration: default_tick_duration,
wheelCount: default_wheel_count,
wheel: createWheel(default_wheel_count),
wheelCursor: 0,
mask: default_wheel_count - 1,
roundDuration: default_tick_duration * default_wheel_count,
}
}
func NewTimerWheelWithTick(tick time.Duration) *TimerWheel {
return &TimerWheel{
tickDuration: tick,
wheelCount: default_wheel_count,
wheel: createWheel(default_wheel_count),
wheelCursor: 0,
mask: default_wheel_count - 1,
roundDuration: default_tick_duration * default_wheel_count,
}
}
func (t *TimerWheel) Start() {
t.lock.Lock()
t.tick = time.NewTicker(t.tickDuration)
defer t.lock.Unlock()
go func() {
for {
select {
case <-t.tick.C:
t.wheelCursor++
if t.wheelCursor == t.wheelCount {
t.wheelCursor = 0
}
iterator := t.wheel[t.wheelCursor]
tasks := t.fetchExpiredTimeouts(iterator)
t.notifyExpiredTimeOut(tasks)
}
}
}()
}
func (t *TimerWheel) Stop() {
t.tick.Stop()
}
func createWheel(wheelCount int) []*Iterator {
arr := make([]*Iterator, wheelCount)
for v := 0; v < wheelCount; v++ {
arr[v] = &Iterator{items: make(map[string]*WheelTimeOut)}
}
return arr
}
func (t *TimerWheel) AddTask(task TimerTask, delay time.Duration) (string, error) {
if task == nil {
return "", errors.New("task is empty")
}
if delay <= 0 {
return "", errors.New("delay Must be greater than zero")
}
timeOut := &WheelTimeOut{
delay: delay,
task: task,
}
tid, err := t.scheduleTimeOut(timeOut)
return tid, err
}
func (t *TimerWheel) RemoveTask(taskId string) error {
t.lock.Lock()
defer t.lock.Unlock()
for _, it := range t.wheel {
for k, _ := range it.items {
if taskId == k {
delete(it.items, k)
}
}
}
return nil
}
func (t *TimerWheel) scheduleTimeOut(timeOut *WheelTimeOut) (string, error) {
if timeOut.delay < t.tickDuration {
timeOut.delay = t.tickDuration
}
lastRoundDelay := timeOut.delay % t.roundDuration
lastTickDelay := timeOut.delay % t.tickDuration
relativeIndex := lastRoundDelay / t.tickDuration
if lastTickDelay != 0 {
relativeIndex = relativeIndex + 1
}
remainingRounds := timeOut.delay / t.roundDuration
if lastRoundDelay == 0 {
remainingRounds = remainingRounds - 1
}
t.lock.Lock()
defer t.lock.Unlock()
stopIndex := t.wheelCursor + int(relativeIndex)
if stopIndex >= t.wheelCount {
stopIndex = stopIndex - t.wheelCount
timeOut.rounds = int(remainingRounds) + 1
} else {
timeOut.rounds = int(remainingRounds)
}
timeOut.index = stopIndex
item := t.wheel[stopIndex]
if item == nil {
item = &Iterator{
items: make(map[string]*WheelTimeOut),
}
}
// In case GetGuid is not random enough ??
for i := 0; i < 16; i++ {
key, err := GetGuid()
if err != nil {
return "", err
}
if _, ok := item.items[key]; !ok {
// Good, no collision
item.items[key] = timeOut
t.wheel[stopIndex] = item
return key, nil
}
}
return "", errors.New("Failed to create unique task key")
}
func (t *TimerWheel) fetchExpiredTimeouts(iterator *Iterator) []*WheelTimeOut {
t.lock.Lock()
defer t.lock.Unlock()
task := []*WheelTimeOut{}
for k, v := range iterator.items {
if v.rounds <= 0 {
task = append(task, v)
delete(iterator.items, k)
} else {
v.rounds--
}
}
return task
}
func (t *TimerWheel) notifyExpiredTimeOut(tasks []*WheelTimeOut) {
for _, task := range tasks {
go task.task.Expire()
}
}