-
Notifications
You must be signed in to change notification settings - Fork 65
/
timer.go
484 lines (397 loc) · 8.22 KB
/
timer.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package timewheel
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
)
const (
typeTimer taskType = iota
typeTicker
modeIsCircle = true
modeNotCircle = false
modeIsAsync = true
modeNotAsync = false
)
type taskType int64
type taskID int64
type Task struct {
delay time.Duration
id taskID
round int
callback func()
async bool
stop bool
circle bool
// circleNum int
}
// for sync.Pool
func (t *Task) Reset() {
t.delay = 0
t.id = 0
t.round = 0
t.callback = nil
t.async = false
t.stop = false
t.circle = false
}
type optionCall func(*TimeWheel) error
func TickSafeMode() optionCall {
return func(o *TimeWheel) error {
o.tickQueue = make(chan time.Time, 10)
return nil
}
}
// todo:
// func SetSyncPool(state bool) optionCall {
// return func(o *TimeWheel) error {
// o.syncPool = state
// return nil
// }
// }
type TimeWheel struct {
randomID int64
tick time.Duration
ticker *time.Ticker
tickQueue chan time.Time
bucketsNum int
buckets []map[taskID]*Task // key: added item, value: *Task
bucketIndexes map[taskID]int // key: added item, value: bucket position
currentIndex int
onceStart sync.Once
stopC chan struct{}
exited bool
sync.RWMutex
}
// NewTimeWheel create new time wheel
func NewTimeWheel(tick time.Duration, bucketsNum int, options ...optionCall) (*TimeWheel, error) {
if tick.Milliseconds() < 1 {
return nil, errors.New("invalid params, must tick >= 1 ms")
}
if bucketsNum <= 0 {
return nil, errors.New("invalid params, must bucketsNum > 0")
}
tw := &TimeWheel{
// tick
tick: tick,
tickQueue: make(chan time.Time, 10),
// store
bucketsNum: bucketsNum,
bucketIndexes: make(map[taskID]int, 1024*100),
buckets: make([]map[taskID]*Task, bucketsNum),
currentIndex: 0,
// signal
stopC: make(chan struct{}),
}
for i := 0; i < bucketsNum; i++ {
tw.buckets[i] = make(map[taskID]*Task, 16)
}
for _, op := range options {
op(tw)
}
return tw, nil
}
// Start start the time wheel
func (tw *TimeWheel) Start() {
// onlye once start
tw.onceStart.Do(
func() {
tw.ticker = time.NewTicker(tw.tick)
go tw.schduler()
go tw.tickGenerator()
},
)
}
func (tw *TimeWheel) tickGenerator() {
if tw.tickQueue != nil {
return
}
for !tw.exited {
select {
case <-tw.ticker.C:
select {
case tw.tickQueue <- time.Now():
default:
panic("raise long time blocking")
}
}
}
}
func (tw *TimeWheel) schduler() {
queue := tw.ticker.C
if tw.tickQueue == nil {
queue = tw.tickQueue
}
for {
select {
case <-queue:
tw.handleTick()
case <-tw.stopC:
tw.exited = true
tw.ticker.Stop()
return
}
}
}
// Stop stop the time wheel
func (tw *TimeWheel) Stop() {
tw.stopC <- struct{}{}
}
func (tw *TimeWheel) collectTask(task *Task) {
index := tw.bucketIndexes[task.id]
delete(tw.bucketIndexes, task.id)
delete(tw.buckets[index], task.id)
// todo:
// if tw.syncPool {
// defaultTaskPool.put(task)
// }
}
func (tw *TimeWheel) handleTick() {
tw.Lock()
defer tw.Unlock()
bucket := tw.buckets[tw.currentIndex]
for k, task := range bucket {
if task.stop {
tw.collectTask(task)
continue
}
if bucket[k].round > 0 {
bucket[k].round--
continue
}
if task.async {
go task.callback()
} else {
// optimize gopool
task.callback()
}
// circle
if task.circle == true {
tw.collectTask(task)
tw.putCircle(task, modeIsCircle)
continue
}
// gc
tw.collectTask(task)
}
if tw.currentIndex == tw.bucketsNum-1 {
tw.currentIndex = 0
return
}
tw.currentIndex++
}
// Add add an task
func (tw *TimeWheel) Add(delay time.Duration, callback func()) *Task {
return tw.addAny(delay, callback, modeNotCircle, modeIsAsync)
}
// AddCron add interval task
func (tw *TimeWheel) AddCron(delay time.Duration, callback func()) *Task {
return tw.addAny(delay, callback, modeIsCircle, modeIsAsync)
}
func (tw *TimeWheel) addAny(delay time.Duration, callback func(), circle, async bool) *Task {
if delay <= 0 {
delay = tw.tick
}
id := tw.genUniqueID()
task := new(Task)
// todo:
// var task *Task
// if tw.syncPool {
// task = defaultTaskPool.get()
// }
task.delay = delay
task.id = id
task.callback = callback
task.circle = circle
task.async = async // refer to src/runtime/time.go
tw.put(task)
return task
}
func (tw *TimeWheel) put(task *Task) {
tw.Lock()
defer tw.Unlock()
tw.store(task, false)
}
func (tw *TimeWheel) putCircle(task *Task, circleMode bool) {
tw.store(task, circleMode)
}
func (tw *TimeWheel) store(task *Task, circleMode bool) {
round := tw.calculateRound(task.delay)
index := tw.calculateIndex(task.delay)
if round > 0 && circleMode {
task.round = round - 1
} else {
task.round = round
}
tw.bucketIndexes[task.id] = index
tw.buckets[index][task.id] = task
}
func (tw *TimeWheel) calculateRound(delay time.Duration) (round int) {
delaySeconds := delay.Seconds()
tickSeconds := tw.tick.Seconds()
round = int(delaySeconds / tickSeconds / float64(tw.bucketsNum))
return
}
func (tw *TimeWheel) calculateIndex(delay time.Duration) (index int) {
delaySeconds := delay.Seconds()
tickSeconds := tw.tick.Seconds()
index = (int(float64(tw.currentIndex) + delaySeconds/tickSeconds)) % tw.bucketsNum
return
}
func (tw *TimeWheel) Remove(task *Task) error {
// tw.removeC <- task
tw.remove(task)
return nil
}
func (tw *TimeWheel) remove(task *Task) {
tw.Lock()
defer tw.Unlock()
tw.collectTask(task)
}
func (tw *TimeWheel) NewTimer(delay time.Duration) *Timer {
queue := make(chan bool, 1) // buf = 1, refer to src/time/sleep.go
task := tw.addAny(delay,
func() {
notifyChannel(queue)
},
modeNotCircle,
modeNotAsync,
)
// init timer
ctx, cancel := context.WithCancel(context.Background())
timer := &Timer{
tw: tw,
C: queue, // faster
task: task,
Ctx: ctx,
cancel: cancel,
}
return timer
}
func (tw *TimeWheel) AfterFunc(delay time.Duration, callback func()) *Timer {
queue := make(chan bool, 1)
task := tw.addAny(delay,
func() {
callback()
notifyChannel(queue)
},
modeNotCircle, modeIsAsync,
)
// init timer
ctx, cancel := context.WithCancel(context.Background())
timer := &Timer{
tw: tw,
C: queue, // faster
task: task,
Ctx: ctx,
cancel: cancel,
fn: callback,
}
return timer
}
func (tw *TimeWheel) NewTicker(delay time.Duration) *Ticker {
queue := make(chan bool, 1)
task := tw.addAny(delay,
func() {
notifyChannel(queue)
},
modeIsCircle,
modeNotAsync,
)
// init ticker
ctx, cancel := context.WithCancel(context.Background())
ticker := &Ticker{
task: task,
tw: tw,
C: queue,
Ctx: ctx,
cancel: cancel,
}
return ticker
}
func (tw *TimeWheel) After(delay time.Duration) <-chan time.Time {
queue := make(chan time.Time, 1)
tw.addAny(delay,
func() {
queue <- time.Now()
},
modeNotCircle, modeNotAsync,
)
return queue
}
func (tw *TimeWheel) Sleep(delay time.Duration) {
queue := make(chan bool, 1)
tw.addAny(delay,
func() {
queue <- true
},
modeNotCircle, modeNotAsync,
)
<-queue
}
// similar to golang std timer
type Timer struct {
task *Task
tw *TimeWheel
fn func() // external custom func
stopFn func() // call function when timer stop
C chan bool
cancel context.CancelFunc
Ctx context.Context
}
func (t *Timer) Reset(delay time.Duration) {
// first stop old task
t.task.stop = true
// make new task
var task *Task
if t.fn != nil { // use AfterFunc
task = t.tw.addAny(delay,
func() {
t.fn()
notifyChannel(t.C)
},
modeNotCircle, modeIsAsync, // must async mode
)
} else {
task = t.tw.addAny(delay,
func() {
notifyChannel(t.C)
},
modeNotCircle, modeNotAsync)
}
t.task = task
}
func (t *Timer) Stop() {
if t.stopFn != nil {
t.stopFn()
}
t.task.stop = true
t.cancel()
t.tw.Remove(t.task)
}
func (t *Timer) AddStopFunc(callback func()) {
t.stopFn = callback
}
type Ticker struct {
tw *TimeWheel
task *Task
cancel context.CancelFunc
C chan bool
Ctx context.Context
}
func (t *Ticker) Stop() {
t.task.stop = true
t.cancel()
t.tw.Remove(t.task)
}
func notifyChannel(q chan bool) {
select {
case q <- true:
default:
}
}
func (tw *TimeWheel) genUniqueID() taskID {
id := atomic.AddInt64(&tw.randomID, 1)
return taskID(id)
}