forked from xiaonanln/goTimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.go
191 lines (160 loc) · 3.46 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
package timer
import (
"container/heap"
"fmt"
"os"
"runtime/debug"
"sync"
"time"
)
const (
MIN_TIMER_INTERVAL = 1 * time.Millisecond
)
var (
nextAddSeq uint = 1
)
type Timer struct {
fireTime time.Time
interval time.Duration
callback CallbackFunc
repeat bool
addseq uint
}
func (t *Timer) Cancel() {
t.callback = nil
}
func (t *Timer) IsActive() bool {
return t.callback != nil
}
type _TimerHeap struct {
timers []*Timer
}
func (h *_TimerHeap) Len() int {
return len(h.timers)
}
func (h *_TimerHeap) Less(i, j int) bool {
//log.Println(h.timers[i].fireTime, h.timers[j].fireTime)
t1, t2 := h.timers[i].fireTime, h.timers[j].fireTime
if t1.Before(t2) {
return true
}
if t1.After(t2) {
return false
}
// t1 == t2, making sure Timer with same deadline is fired according to their add order
return h.timers[i].addseq < h.timers[j].addseq
}
func (h *_TimerHeap) Swap(i, j int) {
var tmp *Timer
tmp = h.timers[i]
h.timers[i] = h.timers[j]
h.timers[j] = tmp
}
func (h *_TimerHeap) Push(x interface{}) {
h.timers = append(h.timers, x.(*Timer))
}
func (h *_TimerHeap) Pop() (ret interface{}) {
l := len(h.timers)
h.timers, ret = h.timers[:l-1], h.timers[l-1]
return
}
// Type of callback function
type CallbackFunc func()
var (
timerHeap _TimerHeap
timerHeapLock sync.Mutex
)
func init() {
heap.Init(&timerHeap)
}
// Add a callback which will be called after specified duration
func AddCallback(d time.Duration, callback CallbackFunc) *Timer {
t := &Timer{
fireTime: time.Now().Add(d),
interval: d,
callback: callback,
repeat: false,
}
timerHeapLock.Lock()
t.addseq = nextAddSeq // set addseq when locked
nextAddSeq += 1
heap.Push(&timerHeap, t)
timerHeapLock.Unlock()
return t
}
// Add a timer which calls callback periodly
func AddTimer(d time.Duration, callback CallbackFunc) *Timer {
if d < MIN_TIMER_INTERVAL {
d = MIN_TIMER_INTERVAL
}
t := &Timer{
fireTime: time.Now().Add(d),
interval: d,
callback: callback,
repeat: true,
}
timerHeapLock.Lock()
t.addseq = nextAddSeq // set addseq when locked
nextAddSeq += 1
heap.Push(&timerHeap, t)
timerHeapLock.Unlock()
return t
}
// Tick once for timers
func Tick() {
now := time.Now()
timerHeapLock.Lock()
for {
if timerHeap.Len() <= 0 {
break
}
nextFireTime := timerHeap.timers[0].fireTime
//fmt.Printf(">>> nextFireTime %s, now is %s\n", nextFireTime, now)
if nextFireTime.After(now) {
break
}
t := heap.Pop(&timerHeap).(*Timer)
callback := t.callback
if callback == nil {
continue
}
if !t.repeat {
t.callback = nil
}
// unlock the lock to run callback, because callback may add more callbacks / timers
timerHeapLock.Unlock()
runCallback(callback)
timerHeapLock.Lock()
if t.repeat {
// add Timer back to heap
t.fireTime = t.fireTime.Add(t.interval)
if !t.fireTime.After(now) { // might happen when interval is very small
t.fireTime = now.Add(t.interval)
}
t.addseq = nextAddSeq
nextAddSeq += 1
heap.Push(&timerHeap, t)
}
}
timerHeapLock.Unlock()
}
// Start the self-ticking routine, which ticks per tickInterval
func StartTicks(tickInterval time.Duration) {
go selfTickRoutine(tickInterval)
}
func selfTickRoutine(tickInterval time.Duration) {
for {
time.Sleep(tickInterval)
Tick()
}
}
func runCallback(callback CallbackFunc) {
defer func() {
err := recover()
if err != nil {
fmt.Fprintf(os.Stderr, "Callback %v paniced: %v\n", callback, err)
debug.PrintStack()
}
}()
callback()
}