-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
executable file
·95 lines (80 loc) · 1.43 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
package timer
import (
"github.com/name5566/leaf/conf"
"github.com/name5566/leaf/log"
"runtime"
"time"
)
// one dispatcher per goroutine (goroutine not safe)
type Dispatcher struct {
ChanTimer chan *Timer
}
func NewDispatcher(l int) *Dispatcher {
disp := new(Dispatcher)
disp.ChanTimer = make(chan *Timer, l)
return disp
}
// Timer
type Timer struct {
t *time.Timer
cb func()
}
func (t *Timer) Stop() {
t.t.Stop()
t.cb = nil
}
func (t *Timer) Cb() {
defer func() {
t.cb = nil
if r := recover(); r != nil {
if conf.LenStackBuf > 0 {
buf := make([]byte, conf.LenStackBuf)
l := runtime.Stack(buf, false)
log.Error("%v: %s", r, buf[:l])
} else {
log.Error("%v", r)
}
}
}()
if t.cb != nil {
t.cb()
}
}
func (disp *Dispatcher) AfterFunc(d time.Duration, cb func()) *Timer {
t := new(Timer)
t.cb = cb
t.t = time.AfterFunc(d, func() {
disp.ChanTimer <- t
})
return t
}
// Cron
type Cron struct {
t *Timer
}
func (c *Cron) Stop() {
if c.t != nil {
c.t.Stop()
}
}
func (disp *Dispatcher) CronFunc(cronExpr *CronExpr, _cb func()) *Cron {
c := new(Cron)
now := time.Now()
nextTime := cronExpr.Next(now)
if nextTime.IsZero() {
return c
}
// callback
var cb func()
cb = func() {
defer _cb()
now := time.Now()
nextTime := cronExpr.Next(now)
if nextTime.IsZero() {
return
}
c.t = disp.AfterFunc(nextTime.Sub(now), cb)
}
c.t = disp.AfterFunc(nextTime.Sub(now), cb)
return c
}