-
Notifications
You must be signed in to change notification settings - Fork 1
/
tmr.go
73 lines (63 loc) · 1.22 KB
/
tmr.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
package days
import (
"time"
)
// Timer 定时器
type Timer struct {
*time.Timer
exitCh chan bool
}
// StartTimer 启动定时器
// 与uv_timer_start类似
// uv_timer_start(tmr, first run time, loop time, fn)
// n: 毫秒
// m: 毫秒
func StartTimer(n, m int64, fn func(args ...interface{}) error, args ...interface{}) *Timer {
tmr := time.NewTimer(time.Duration(n) * time.Millisecond)
exitCh := make(chan bool, 0)
doTimer := func() bool {
select {
case <-tmr.C:
case <-exitCh:
// 定时器退出
tmr.Stop()
return true
}
// 执行定时器函数
fn(args)
return false
}
go func() {
if doTimer() == true {
return
}
if m == 0 {
return
}
for {
// 修复时间偏差
// 仅限小时定时和天定时
seconds := m / 1000
now := time.Now()
today := Today()
switch seconds {
case 60:
seconds -= now.Unix() % 60
case 3600:
seconds -= now.Unix() % 3600
case 86400:
seconds -= int64(now.Sub(today).Seconds())
}
// 重置定时器
tmr.Reset(time.Duration(seconds*1000) * time.Millisecond)
if doTimer() == true {
return
}
}
}()
return &Timer{tmr, exitCh}
}
// StopTimer 停止定时器
func StopTimer(tmr *Timer) {
tmr.exitCh <- true
}