-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
192 lines (168 loc) · 5.68 KB
/
module.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Package cron implements cron jobs for the Joe bot library.
// https://github.com/go-joe/joe
package cron
import (
"fmt"
"reflect"
"runtime"
"time"
"github.com/go-joe/joe"
"github.com/robfig/cron/v3"
"go.uber.org/zap"
)
// Parser is the default cron.Parser which is configured to accept standard cron
// schedules with optional seconds.
var Parser = cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)
// A Job is a joe.Module that runs a single cron job on a given interval.
type Job struct {
cron *cron.Cron
schedule cron.Schedule
fun func(joe.EventEmitter) cron.FuncJob
err error // to defer error handling until joe.Module is loaded
// some meta information about the scheduled job
typ, sched string
}
// Event is the event that the ScheduleEvent(…) type functions emit if no custom
// event was passed as argument. It can be useful to implement simple jobs that
// do not require any context but just a schedule that triggers them at an interval.
type Event struct{}
// ScheduleEvent creates a joe.Module that emits one or many events on a given
// cron schedule (e.g. "0 0 * * *"). If the passed schedule is not a valid cron
// schedule as accepted by the package level Parser, the corresponding error
// will be returned when the bot is started.
//
// You can execute this function with only a schedule but no events. In this
// case the job will emit an instance of the cron.Event type that is defined in
// this package. Otherwise all passed events are emitted on the schedule.
func ScheduleEvent(schedule string, events ...interface{}) *Job {
if len(events) == 0 {
events = []interface{}{Event{}}
}
s, err := Parser.Parse(schedule)
if err != nil {
err = fmt.Errorf("invalid cron schedule: %w", err)
}
return &Job{
schedule: s,
err: err,
typ: eventsString(events),
sched: schedule,
fun: func(brain joe.EventEmitter) cron.FuncJob {
return func() {
for _, event := range events {
brain.Emit(event)
}
}
},
}
}
// ScheduleFunc creates a joe.Module that runs the given function on a given
// cron schedule (e.g. "0 0 * * *"). Optionally, the cron schedule can also
// contain seconds, i.e. "30 0 0 * * *".
//
// If the passed schedule is not a valid cron schedule as accepted by the
// package level Parser, the corresponding error will be returned when the bot
// is started.
func ScheduleFunc(schedule string, fun func()) *Job {
s, err := Parser.Parse(schedule)
if err != nil {
err = fmt.Errorf("invalid cron schedule: %w", err)
}
return &Job{
schedule: s,
err: err,
typ: runtime.FuncForPC(reflect.ValueOf(fun).Pointer()).Name(),
sched: schedule,
fun: func(joe.EventEmitter) cron.FuncJob {
return fun
},
}
}
// ScheduleEventEvery creates a joe.Module that emits one or many events on a
// given interval (e.g. every hour). The minimum duration is one second and any
// smaller durations will be rounded up to that.
//
// You can execute this function with only a schedule but no events. In this
// case the job will emit an instance of the cron.Event type that is defined in
// this package. Otherwise all passed events are emitted on the schedule.
func ScheduleEventEvery(schedule time.Duration, events ...interface{}) *Job {
if len(events) == 0 {
events = []interface{}{Event{}}
}
return &Job{
schedule: cron.Every(schedule),
typ: eventsString(events),
sched: fmt.Sprintf("@every %s", schedule),
fun: func(brain joe.EventEmitter) cron.FuncJob {
return func() {
for _, event := range events {
brain.Emit(event)
}
}
},
}
}
// ScheduleFuncEvery creates a joe.Module that runs the given function on a
// given interval (e.g. every hour). The minimum duration is one second and any
// smaller durations will be rounded up to that.
func ScheduleFuncEvery(schedule time.Duration, fun func()) *Job {
return &Job{
schedule: cron.Every(schedule),
typ: runtime.FuncForPC(reflect.ValueOf(fun).Pointer()).Name(),
sched: fmt.Sprintf("@every %s", schedule),
fun: func(joe.EventEmitter) cron.FuncJob {
return fun
},
}
}
func eventsString(events []interface{}) string {
var typ string
for i, evt := range events {
if i > 0 {
typ += ", "
}
typ += fmt.Sprintf("%T", evt)
}
return typ
}
// Apply implements joe.Module by starting a new cron job that may use the event
// emitter from the configuration (if it actually emits events). Jobs that only
// run functions will only require a logger.
func (j *Job) Apply(conf *joe.Config) error {
logger := conf.Logger("cron")
events := conf.EventEmitter()
return j.Start(logger, events)
}
// Start starts the cron job. If you are using the job as joe.Module there is no
// need to start the job explicitly. This function is useful if you want to
// manage jobs yourself if you do not pass them to the bot as joe.Module.
//
// If the job does not actually emit events, the
// passed event emitter will not be used and can be nil.
func (j *Job) Start(logger *zap.Logger, events joe.EventEmitter) error {
if j.err != nil {
return j.err
}
errLogger, _ := zap.NewStdLogAt(logger, zap.ErrorLevel) // returned error can be ignored because it can never happen with zap.ErrorLevel
cronLogger := cron.PrintfLogger(errLogger)
logger.Info("Registering new cron job",
zap.String("typ", j.typ),
zap.String("schedule", j.sched),
zap.Time("next_run", j.schedule.Next(time.Now())),
)
job := j.fun(events)
j.cron = cron.New(cron.WithLogger(cronLogger))
j.cron.Schedule(j.schedule, job)
j.cron.Start()
return nil
}
// Close stops the cron job.
func (j *Job) Close() error {
// The job may be nil if the used cron expression was invalid.
if j.cron != nil {
j.cron.Stop()
}
return nil
}