-
Notifications
You must be signed in to change notification settings - Fork 2
/
timewheel.go
213 lines (195 loc) · 4.94 KB
/
timewheel.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
201
202
203
204
205
206
207
208
209
210
211
212
213
package timewheel
import (
"container/list"
"fmt"
"log"
"sync"
"time"
)
var (
DefaultSlotInterval = time.Second * 1
DefaultSlotNum = 60
)
type timer struct {
timerID string
interval time.Duration
data interface{}
}
type timerRecord struct {
slot int
wheel int
el *list.Element
}
var tw *TimeWheel
type TimeWheel struct {
mu sync.RWMutex
ticker *time.Ticker
slotInterval time.Duration
slotNum int
// map[wheel][slot]timerItemList
wheelTimerList map[int]map[int]*list.List
currentPos int
currentWheel int
callback func(interface{})
startChan chan bool
stopChan chan bool
timerRecordMap map[string]timerRecord
}
// New 实例化时间轮
func New(slotDuration time.Duration, slotNum int, callback func(interface{})) *TimeWheel {
if slotDuration <= 0 || slotNum <= 0 {
slotDuration = time.Second
slotNum = 60
}
return &TimeWheel{
slotInterval: slotDuration,
slotNum: 60,
// map[wheel][slot]timerItemList
wheelTimerList: make(map[int]map[int]*list.List),
callback: callback,
startChan: make(chan bool, 1),
stopChan: make(chan bool, 1),
timerRecordMap: make(map[string]timerRecord),
}
}
// Start start timewheel
func (tw *TimeWheel) Start() {
// 避免重复操作
select {
case tw.startChan <- true:
default:
fmt.Println("timewheel is already running, exit")
return
}
// 启动时间轮的内部定时器
tw.ticker = time.NewTicker(tw.slotInterval)
go func() {
for {
select {
case <-tw.ticker.C:
tw.tickerHandler()
case <-tw.stopChan:
return
}
}
}()
}
// AddTimer add timer
func (tw *TimeWheel) AddTimer(timerID string, interval time.Duration, data interface{}) (success bool) {
tw.mu.Lock()
defer tw.mu.Unlock()
if len(tw.startChan) == 0 {
log.Println(" timewheel has not been started")
return false
}
tm := timer{
timerID: timerID,
interval: interval,
data: data,
}
// 已经存在的定时器id,将会停止旧的定时器,并创建新的定时器
if _, ok := tw.timerRecordMap[timerID]; ok {
l := tw.wheelTimerList[tw.timerRecordMap[timerID].wheel][tw.timerRecordMap[timerID].slot]
el := tw.timerRecordMap[timerID].el
if l == nil || el == nil {
log.Println(" timer has exist")
return false
}
l.Remove(el)
tw.wheelTimerList[tw.timerRecordMap[timerID].wheel][tw.timerRecordMap[timerID].slot] = l
}
// 计算定时器要插入的位置
calSlotPos := (tw.currentPos + int(tm.interval)/int(tw.slotInterval)) % tw.slotNum // calculate the timer's wheel
calWheel := (tw.currentPos+int(tm.interval)/int(tw.slotInterval))/tw.slotNum + tw.currentWheel
if tw.wheelTimerList[calWheel] == nil {
tw.wheelTimerList[calWheel] = make(map[int]*list.List)
}
// 获取定时器链表
l := tw.wheelTimerList[calWheel][calSlotPos]
if l == nil {
l = list.New()
}
// 定时器插入链表
el := l.PushBack(tm)
tw.wheelTimerList[calWheel][calSlotPos] = l
// 保存定时器信息,id及位置
tw.timerRecordMap[tm.timerID] = timerRecord{
slot: calSlotPos,
wheel: calWheel,
el: el,
}
return true
}
// StopTimer stop timer
func (tw *TimeWheel) StopTimer(timerID string) (success bool) {
tw.mu.Lock()
defer tw.mu.Unlock()
// 定时器id存在检查
if _, ok := tw.timerRecordMap[timerID]; !ok {
log.Println("timer does not exist")
return false
}
l := tw.wheelTimerList[tw.timerRecordMap[timerID].wheel][tw.timerRecordMap[timerID].slot]
el := tw.timerRecordMap[timerID].el
// 空队列及空元素判断拦截,避免crash
if l == nil || el == nil {
return
}
l.Remove(el)
tw.wheelTimerList[tw.timerRecordMap[timerID].wheel][tw.timerRecordMap[timerID].slot] = l
// 删除定时器记录
delete(tw.timerRecordMap, timerID)
return true
}
// Stop stop the timewheel
func (tw *TimeWheel) Stop() (success bool) {
// 避免重复操作
select {
case <-tw.startChan:
tw.ticker.Stop()
tw.stopChan <- true
return true
default:
log.Println("timewheel has stopped,exit.")
return false
}
}
// tickerHandler
func (tw *TimeWheel) tickerHandler() {
tw.mu.Lock()
defer tw.mu.Unlock()
// 时间轮转动
tw.currentPos++
// 时间轮执行一圈后,时间轮递增,时间槽计数复位
if tw.currentPos%tw.slotNum == 0 {
delete(tw.wheelTimerList, tw.currentWheel)
tw.currentWheel++
tw.currentPos = 0
}
// 跳过空的时间槽
l := tw.wheelTimerList[tw.currentWheel][tw.currentPos]
if l == nil {
return
}
// 遍历时间时间槽的定时器链表
for e := l.Front(); e != nil; e = e.Next() {
tm, _ := e.Value.(timer)
delete(tw.timerRecordMap, tm.timerID)
go tw.callback(tm.data)
}
// 删除时间槽的定时器链表
delete(tw.wheelTimerList[tw.currentWheel], tw.currentPos)
}
func Start(callback func(interface{})) {
tw = New(DefaultSlotInterval, DefaultSlotNum, callback)
tw.Start()
}
func AddTimer(key string, interval time.Duration, data interface{}) {
tw.AddTimer(key, interval, data)
}
func StopTimer(key string) {
tw.StopTimer(key)
}
func Stop() {
tw.Stop()
}