-
Notifications
You must be signed in to change notification settings - Fork 2
/
onTime.go
81 lines (67 loc) · 1.81 KB
/
onTime.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
package time
import (
"fmt"
"time"
)
const (
OnDay = iota
OnHour
OnMin
OnSecond
)
//OnTimer 定时发生器
//OnDay 每天零时执行callback
//OnHour 每个小时执行callback
//OnMin 每分钟执行callback
//OnSecond 每秒钟执行callback
//如果执行过程出现error, 则通过chan error获取具体错误原因
/*
##### Example
```go
//定时每天执行callback函数
package main
import (
"github.com/andy-zhangtao/gogather/zlog"
"github.com/sirupsen/logrus"
"github.com/andy-zhangtao/gogather/time"
)
var z *zlog.Zlog
func callback() error {
logrus.WithFields(z.Fields(logrus.Fields{"from": "callback"})).Info("callback")
return nil
}
func main() {
z = zlog.GetZlog()
time.OnTimer(time.OnDay, 1, callback)
}
```
*/
func OnTimer(kind, duration int, callback func() error) (chan error) {
var next time.Time
errChan := make(chan error)
for {
now := time.Now()
switch kind {
case OnDay:
next = now.Add(time.Hour * time.Duration(duration*24))
next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
case OnHour:
next = now.Add(time.Minute * time.Duration(duration*60))
next = time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), 0, 0, 0, next.Location())
case OnMin:
next = now.Add(time.Second * time.Duration(duration*60))
next = time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), next.Minute(), 0, 0, next.Location())
case OnSecond:
next = now.Add(time.Millisecond * time.Duration(duration*1000))
next = time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), next.Minute(), next.Second(), 0, next.Location())
}
t := time.NewTimer(next.Sub(now))
fmt.Printf("下次采集时间为[%s]\n", next.Format("20060102150405"))
select {
case <-t.C:
if err := callback(); err != nil {
return errChan
}
}
}
}