forked from lonng/nano
/
timer.go
215 lines (183 loc) · 5.68 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
package nano
import (
"fmt"
"log"
"math"
"sync"
"sync/atomic"
"time"
)
const (
loopForever = -1
)
var (
// timerManager manager for all timers
timerManager = &struct {
incrementID int64 // auto increment id
timers map[int64]*Timer // all timers
muClosingTimer sync.RWMutex
closingTimer []int64
muCreatedTimer sync.RWMutex
createdTimer []*Timer
}{}
// timerPrecision indicates the precision of timer, default is time.Second
timerPrecision = time.Second
// globalTicker represents global ticker that all cron job will be executed
// in globalTicker.
globalTicker *time.Ticker
)
type (
// TimerFunc represents a function which will be called periodically in main
// logic gorontine.
TimerFunc func()
// TimerCondition represents a checker that returns true when cron job needs
// to execute
TimerCondition interface {
Check(now time.Time) bool
}
// Timer represents a cron job
Timer struct {
id int64 // timer id
fn TimerFunc // function that execute
createAt int64 // timer create time
interval time.Duration // execution interval
condition TimerCondition // condition to cron job execution
elapse int64 // total elapse time
closed int32 // is timer closed
counter int // counter
}
)
func init() {
timerManager.timers = map[int64]*Timer{}
}
// ID returns id of current timer
func (t *Timer) ID() int64 {
return t.id
}
// Stop turns off a timer. After Stop, fn will not be called forever
func (t *Timer) Stop() {
if atomic.AddInt32(&t.closed, 1) != 1 {
return
}
t.counter = 0
}
// execute job function with protection
func safecall(id int64, fn TimerFunc) {
defer func() {
if err := recover(); err != nil {
log.Println(fmt.Sprintf("Call timer function error, TimerID=%d, Error=%v", id, err))
println(stack())
}
}()
fn()
}
func cron() {
if len(timerManager.createdTimer) > 0 {
timerManager.muCreatedTimer.Lock()
for _, t := range timerManager.createdTimer {
timerManager.timers[t.id] = t
}
timerManager.createdTimer = timerManager.createdTimer[:0]
timerManager.muCreatedTimer.Unlock()
}
if len(timerManager.timers) < 1 {
return
}
now := time.Now()
unn := now.UnixNano()
for id, t := range timerManager.timers {
if t.counter == loopForever || t.counter > 0 {
// condition timer
if t.condition != nil {
if t.condition.Check(now) {
safecall(id, t.fn)
}
continue
}
// execute job
if t.createAt+t.elapse <= unn {
safecall(id, t.fn)
t.elapse += int64(t.interval)
// update timer counter
if t.counter != loopForever && t.counter > 0 {
t.counter--
}
}
}
if t.counter == 0 {
timerManager.muClosingTimer.Lock()
timerManager.closingTimer = append(timerManager.closingTimer, t.id)
timerManager.muClosingTimer.Unlock()
continue
}
}
if len(timerManager.closingTimer) > 0 {
timerManager.muClosingTimer.Lock()
for _, id := range timerManager.closingTimer {
delete(timerManager.timers, id)
}
timerManager.closingTimer = timerManager.closingTimer[:0]
timerManager.muClosingTimer.Unlock()
}
}
// NewTimer returns a new Timer containing a function that will be called
// with a period specified by the duration argument. It adjusts the intervals
// for slow receivers.
// The duration d must be greater than zero; if not, NewTimer will panic.
// Stop the timer to release associated resources.
func NewTimer(interval time.Duration, fn TimerFunc) *Timer {
return NewCountTimer(interval, loopForever, fn)
}
// NewCountTimer returns a new Timer containing a function that will be called
// with a period specified by the duration argument. After count times, timer
// will be stopped automatically, It adjusts the intervals for slow receivers.
// The duration d must be greater than zero; if not, NewCountTimer will panic.
// Stop the timer to release associated resources.
func NewCountTimer(interval time.Duration, count int, fn TimerFunc) *Timer {
if fn == nil {
panic("nano/timer: nil timer function")
}
if interval <= 0 {
panic("non-positive interval for NewTimer")
}
t := &Timer{
id: atomic.AddInt64(&timerManager.incrementID, 1),
fn: fn,
createAt: time.Now().UnixNano(),
interval: interval,
elapse: int64(interval), // first execution will be after interval
counter: count,
}
timerManager.muCreatedTimer.Lock()
timerManager.createdTimer = append(timerManager.createdTimer, t)
timerManager.muCreatedTimer.Unlock()
return t
}
// NewAfterTimer returns a new Timer containing a function that will be called
// after duration that specified by the duration argument.
// The duration d must be greater than zero; if not, NewAfterTimer will panic.
// Stop the timer to release associated resources.
func NewAfterTimer(duration time.Duration, fn TimerFunc) *Timer {
return NewCountTimer(duration, 1, fn)
}
// NewCondTimer returns a new Timer containing a function that will be called
// when condition satisfied that specified by the condition argument.
// The duration d must be greater than zero; if not, NewCondTimer will panic.
// Stop the timer to release associated resources.
func NewCondTimer(condition TimerCondition, fn TimerFunc) *Timer {
if condition == nil {
panic("nano/timer: nil condition")
}
t := NewCountTimer(time.Duration(math.MaxInt64), loopForever, fn)
t.condition = condition
return t
}
// SetTimerPrecision set the ticker precision, and time precision can not less
// than a Millisecond, and can not change after application running. The default
// precision is time.Second
func SetTimerPrecision(precision time.Duration) {
if precision < time.Millisecond {
panic("time precision can not less than a Millisecond")
}
timerPrecision = precision
}