-
Notifications
You must be signed in to change notification settings - Fork 3
/
cron.go
101 lines (84 loc) · 1.67 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
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
package cron
import (
"context"
"github.com/go-bamboo/pkg/log"
"github.com/go-bamboo/pkg/rescue"
"github.com/robfig/cron/v3"
"go.uber.org/zap/zapcore"
)
type (
ConsumeHandle func(ctx context.Context) error
Pair struct {
spec string
handler ConsumeHandle
}
Cron struct {
cr *cron.Cron
specs []Pair
level zapcore.Level
}
Option func(alc *Cron)
EntryID = cron.EntryID
Job = cron.Job
)
func WithSpec(spec string, handler ConsumeHandle) Option {
return func(alc *Cron) {
alc.specs = append(alc.specs, Pair{spec: spec, handler: handler})
}
}
func WithLogLevel(lvl zapcore.Level) Option {
return func(alc *Cron) {
alc.level = lvl
}
}
// New 新cron
func New(options ...Option) (d *Cron) {
s := &Cron{
level: zapcore.DebugLevel,
}
for _, o := range options {
o(s)
}
stdLogger := NewLogger(log.GetCore(), s.level)
cr := cron.New(
cron.WithSeconds(),
cron.WithLogger(stdLogger),
)
for _, spec := range s.specs {
cr.AddFunc(spec.spec, func() {
defer rescue.Recover()
if err := spec.handler(context.Background()); err != nil {
log.ErrorStack(err)
}
})
}
s.cr = cr
d = s
return
}
func New1(options ...Option) (d *Cron, cf func()) {
d = New(options...)
d.Start()
return d, func() {
d.Stop()
}
}
func (c *Cron) Start() error {
c.cr.Start()
log.Infof("[cron] cron start")
return nil
}
func (c *Cron) Stop() error {
c.cr.Stop()
log.Infof("[cron] cron stop")
return nil
}
func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) {
return c.cr.AddFunc(spec, cmd)
}
func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error) {
return c.cr.AddJob(spec, cmd)
}
func (c *Cron) Remove(id EntryID) {
c.cr.Remove(id)
}