-
Notifications
You must be signed in to change notification settings - Fork 23
/
crontab.go
342 lines (298 loc) · 7.62 KB
/
crontab.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package crontab
import (
"errors"
"fmt"
"log"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// Crontab struct representing cron table
type Crontab struct {
ticker *time.Ticker
jobs []*job
sync.RWMutex
}
// job in cron table
type job struct {
min map[int]struct{}
hour map[int]struct{}
day map[int]struct{}
month map[int]struct{}
dayOfWeek map[int]struct{}
fn interface{}
args []interface{}
sync.RWMutex
}
// tick is individual tick that occures each minute
type tick struct {
min int
hour int
day int
month int
dayOfWeek int
}
// New initializes and returns new cron table
func New() *Crontab {
return new(time.Minute)
}
// new creates new crontab, arg provided for testing purpose
func new(t time.Duration) *Crontab {
c := &Crontab{
ticker: time.NewTicker(t),
jobs: []*job{},
}
go func() {
for t := range c.ticker.C {
c.runScheduled(t)
}
}()
return c
}
// AddJob to cron table
//
// Returns error if:
//
// * Cron syntax can't be parsed or out of bounds
//
// * fn is not function
//
// * Provided args don't match the number and/or the type of fn args
func (c *Crontab) AddJob(schedule string, fn interface{}, args ...interface{}) error {
j, err := parseSchedule(schedule)
c.Lock()
defer c.Unlock()
if err != nil {
return err
}
if fn == nil || reflect.ValueOf(fn).Kind() != reflect.Func {
return fmt.Errorf("Cron job must be func()")
}
fnType := reflect.TypeOf(fn)
if len(args) != fnType.NumIn() {
return fmt.Errorf("Number of func() params and number of provided params doesn't match")
}
for i := 0; i < fnType.NumIn(); i++ {
a := args[i]
t1 := fnType.In(i)
t2 := reflect.TypeOf(a)
if t1 != t2 {
if t1.Kind() != reflect.Interface {
return fmt.Errorf("Param with index %d shold be `%s` not `%s`", i, t1, t2)
}
if !t2.Implements(t1) {
return fmt.Errorf("Param with index %d of type `%s` doesn't implement interface `%s`", i, t2, t1)
}
}
}
// all checked, add job to cron tab
j.fn = fn
j.args = args
c.jobs = append(c.jobs, j)
return nil
}
// MustAddJob is like AddJob but panics if there is an problem with job
//
// It simplifies initialization, since we usually add jobs at the beggining so you won't have to check for errors (it will panic when program starts).
// It is a similar aproach as go's std lib package `regexp` and `regexp.Compile()` `regexp.MustCompile()`
// MustAddJob will panic if:
//
// * Cron syntax can't be parsed or out of bounds
//
// * fn is not function
//
// * Provided args don't match the number and/or the type of fn args
func (c *Crontab) MustAddJob(schedule string, fn interface{}, args ...interface{}) {
if err := c.AddJob(schedule, fn, args...); err != nil {
panic(err)
}
}
// Shutdown the cron table schedule
//
// Once stopped, it can't be restarted.
// This function is pre-shuttdown helper for your app, there is no Start/Stop functionallity with crontab package.
func (c *Crontab) Shutdown() {
c.ticker.Stop()
}
// Clear all jobs from cron table
func (c *Crontab) Clear() {
c.Lock()
c.jobs = []*job{}
c.Unlock()
}
// RunAll jobs in cron table, shcheduled or not
func (c *Crontab) RunAll() {
c.RLock()
defer c.RUnlock()
for _, j := range c.jobs {
go j.run()
}
}
// RunScheduled jobs
func (c *Crontab) runScheduled(t time.Time) {
tick := getTick(t)
c.RLock()
defer c.RUnlock()
for _, j := range c.jobs {
if j.tick(tick) {
go j.run()
}
}
}
// run the job using reflection
// Recover from panic although all functions and params are checked by AddJob, but you never know.
func (j *job) run() {
j.RLock()
defer func() {
if r := recover(); r != nil {
log.Println("Crontab error", r)
}
}()
v := reflect.ValueOf(j.fn)
rargs := make([]reflect.Value, len(j.args))
for i, a := range j.args {
rargs[i] = reflect.ValueOf(a)
}
j.RUnlock()
v.Call(rargs)
}
// tick decides should the job be lauhcned at the tick
func (j *job) tick(t tick) bool {
j.RLock()
defer j.RUnlock()
if _, ok := j.min[t.min]; !ok {
return false
}
if _, ok := j.hour[t.hour]; !ok {
return false
}
// cummulative day and dayOfWeek, as it should be
_, day := j.day[t.day]
_, dayOfWeek := j.dayOfWeek[t.dayOfWeek]
if !day && !dayOfWeek {
return false
}
if _, ok := j.month[t.month]; !ok {
return false
}
return true
}
// regexps for parsing schedule string
var (
matchSpaces = regexp.MustCompile(`\s+`)
matchN = regexp.MustCompile(`(.*)/(\d+)`)
matchRange = regexp.MustCompile(`^(\d+)-(\d+)$`)
)
// parseSchedule string and creates job struct with filled times to launch, or error if synthax is wrong
func parseSchedule(s string) (*job, error) {
var err error
j := &job{}
j.Lock()
defer j.Unlock()
s = matchSpaces.ReplaceAllLiteralString(s, " ")
parts := strings.Split(s, " ")
if len(parts) != 5 {
return j, errors.New("Schedule string must have five components like * * * * *")
}
j.min, err = parsePart(parts[0], 0, 59)
if err != nil {
return j, err
}
j.hour, err = parsePart(parts[1], 0, 23)
if err != nil {
return j, err
}
j.day, err = parsePart(parts[2], 1, 31)
if err != nil {
return j, err
}
j.month, err = parsePart(parts[3], 1, 12)
if err != nil {
return j, err
}
j.dayOfWeek, err = parsePart(parts[4], 0, 6)
if err != nil {
return j, err
}
// day/dayOfWeek combination
switch {
case len(j.day) < 31 && len(j.dayOfWeek) == 7: // day set, but not dayOfWeek, clear dayOfWeek
j.dayOfWeek = make(map[int]struct{})
case len(j.dayOfWeek) < 7 && len(j.day) == 31: // dayOfWeek set, but not day, clear day
j.day = make(map[int]struct{})
default:
// both day and dayOfWeek are * or both are set, use combined
// i.e. don't do anything here
}
return j, nil
}
// parsePart parse individual schedule part from schedule string
func parsePart(s string, min, max int) (map[int]struct{}, error) {
r := make(map[int]struct{})
// wildcard pattern
if s == "*" {
for i := min; i <= max; i++ {
r[i] = struct{}{}
}
return r, nil
}
// */2 1-59/5 pattern
if matches := matchN.FindStringSubmatch(s); matches != nil {
localMin := min
localMax := max
if matches[1] != "" && matches[1] != "*" {
if rng := matchRange.FindStringSubmatch(matches[1]); rng != nil {
localMin, _ = strconv.Atoi(rng[1])
localMax, _ = strconv.Atoi(rng[2])
if localMin < min || localMax > max {
return nil, fmt.Errorf("Out of range for %s in %s. %s must be in range %d-%d", rng[1], s, rng[1], min, max)
}
} else {
return nil, fmt.Errorf("Unable to parse %s part in %s", matches[1], s)
}
}
n, _ := strconv.Atoi(matches[2])
for i := localMin; i <= localMax; i += n {
r[i] = struct{}{}
}
return r, nil
}
// 1,2,4 or 1,2,10-15,20,30-45 pattern
parts := strings.Split(s, ",")
for _, x := range parts {
if rng := matchRange.FindStringSubmatch(x); rng != nil {
localMin, _ := strconv.Atoi(rng[1])
localMax, _ := strconv.Atoi(rng[2])
if localMin < min || localMax > max {
return nil, fmt.Errorf("Out of range for %s in %s. %s must be in range %d-%d", x, s, x, min, max)
}
for i := localMin; i <= localMax; i++ {
r[i] = struct{}{}
}
} else if i, err := strconv.Atoi(x); err == nil {
if i < min || i > max {
return nil, fmt.Errorf("Out of range for %d in %s. %d must be in range %d-%d", i, s, i, min, max)
}
r[i] = struct{}{}
} else {
return nil, fmt.Errorf("Unable to parse %s part in %s", x, s)
}
}
if len(r) == 0 {
return nil, fmt.Errorf("Unable to parse %s", s)
}
return r, nil
}
// getTick returns the tick struct from time
func getTick(t time.Time) tick {
return tick{
min: t.Minute(),
hour: t.Hour(),
day: t.Day(),
month: int(t.Month()),
dayOfWeek: int(t.Weekday()),
}
}