-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcron.go
53 lines (43 loc) · 1.02 KB
/
cron.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
package hfw
import (
"time"
"github.com/hsyan2008/hfw/common"
cron "github.com/robfig/cron/v3"
)
var crontab *cron.Cron
func init() {
crontab = cron.New(cron.WithSeconds())
crontab.Start()
}
func AddCron(spec string, cmd func()) (cron.EntryID, error) {
return crontab.AddFunc(spec, cmd)
}
func StopCron() {
crontab.Stop()
}
func AddWrapCron(spec string, cmd func(httpCtx *HTTPContext) error) (cron.EntryID, error) {
return AddCron(spec, WrapCron(cmd))
}
func DoWrapCron(spec string, cmd func(httpCtx *HTTPContext) error) (cron.EntryID, error) {
f := WrapCron(cmd)
go f()
return AddCron(spec, f)
}
func WrapCron(cmd func(httpCtx *HTTPContext) error) func() {
return func() {
httpCtx := NewHTTPContext()
defer httpCtx.Cancel()
defer func(now time.Time) {
if err := recover(); err != nil {
if err != ErrStopRun {
httpCtx.Warn(err, string(common.GetStack()))
}
}
httpCtx.Infof("CostTime: %s", time.Since(now))
}(time.Now())
err := cmd(httpCtx)
if err != nil {
httpCtx.Warn(err)
}
}
}