-
Notifications
You must be signed in to change notification settings - Fork 1
/
timer.go
50 lines (40 loc) · 764 Bytes
/
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
package minq
import (
"time"
)
type timerCb func()
type timer struct {
ts *timerSet
cb timerCb
deadline time.Time
}
// This is a simple implementation of unsorted timers.
// TODO(ekr@rtfm.com): Need a better data structure.
type timerSet struct {
ts []*timer
}
func newTimers() *timerSet {
return &timerSet{nil}
}
func (ts *timerSet) start(cb timerCb, delayMs uint32) *timer {
t := timer{
ts,
cb,
time.Now().Add(time.Millisecond * time.Duration(delayMs)),
}
ts.ts = append(ts.ts, &t)
return &t
}
func (ts *timerSet) check(now time.Time) {
for i, t := range ts.ts {
if now.After(t.deadline) {
ts.ts = append(ts.ts[:i], ts.ts[:i+1]...)
if t.cb != nil {
t.cb()
}
}
}
}
func (t *timer) cancel() {
t.cb = nil
}