-
Notifications
You must be signed in to change notification settings - Fork 345
/
job.go
365 lines (311 loc) · 9.06 KB
/
job.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package gocron
import (
"errors"
"fmt"
"log"
"reflect"
"time"
)
var (
ErrTimeFormat = errors.New("time format error")
ErrParamsNotAdapted = errors.New("the number of params is not adapted")
ErrNotAFunction = errors.New("only functions can be schedule into the job queue")
ErrPeriodNotSpecified = errors.New("unspecified job period")
ErrParameterCannotBeNil = errors.New("nil paramaters cannot be used with reflection")
)
// Job struct keeping information about job
type Job struct {
interval uint64 // pause interval * unit between runs
jobFunc string // the job jobFunc to run, func[jobFunc]
unit timeUnit // time units, ,e.g. 'minutes', 'hours'...
atTime time.Duration // optional time at which this job runs
err error // error related to job
loc *time.Location // optional timezone that the atTime is in
lastRun time.Time // datetime of last run
nextRun time.Time // datetime of next run
startDay time.Weekday // Specific day of the week to start on
funcs map[string]interface{} // Map for the function task store
fparams map[string][]interface{} // Map for function and params of function
lock bool // lock the job from running at same time form multiple instances
tags []string // allow the user to tag jobs with certain labels
}
// NewJob creates a new job with the time interval.
func NewJob(interval uint64) *Job {
return &Job{
interval: interval,
loc: loc,
lastRun: time.Unix(0, 0),
nextRun: time.Unix(0, 0),
startDay: time.Sunday,
funcs: make(map[string]interface{}),
fparams: make(map[string][]interface{}),
tags: []string{},
}
}
// True if the job should be run now
func (j *Job) shouldRun() bool {
return time.Now().Unix() >= j.nextRun.Unix()
}
//Run the job and immediately reschedule it
func (j *Job) run() ([]reflect.Value, error) {
if j.lock {
if locker == nil {
return nil, fmt.Errorf("trying to lock %s with nil locker", j.jobFunc)
}
key := getFunctionKey(j.jobFunc)
locker.Lock(key)
defer locker.Unlock(key)
}
result, err := callJobFuncWithParams(j.funcs[j.jobFunc], j.fparams[j.jobFunc])
if err != nil {
return nil, err
}
return result, nil
}
// Err should be checked to ensure an error didn't occur creating the job
func (j *Job) Err() error {
return j.err
}
// Do specifies the jobFunc that should be called every time the job runs
func (j *Job) Do(jobFun interface{}, params ...interface{}) error {
if j.err != nil {
return j.err
}
typ := reflect.TypeOf(jobFun)
if typ.Kind() != reflect.Func {
return ErrNotAFunction
}
fname := getFunctionName(jobFun)
j.funcs[fname] = jobFun
j.fparams[fname] = params
j.jobFunc = fname
now := time.Now().In(j.loc)
if !j.nextRun.After(now) {
j.scheduleNextRun()
}
return nil
}
// DoSafely does the same thing as Do, but logs unexpected panics, instead of unwinding them up the chain
// Deprecated: DoSafely exists due to historical compatibility and will be removed soon. Use Do instead
func (j *Job) DoSafely(jobFun interface{}, params ...interface{}) error {
recoveryWrapperFunc := func() {
defer func() {
if r := recover(); r != nil {
log.Printf("Internal panic occurred: %s", r)
}
}()
_, _ = callJobFuncWithParams(jobFun, params)
}
return j.Do(recoveryWrapperFunc)
}
// At schedules job at specific time of day
// s.Every(1).Day().At("10:30:01").Do(task)
// s.Every(1).Monday().At("10:30:01").Do(task)
func (j *Job) At(t string) *Job {
hour, min, sec, err := formatTime(t)
if err != nil {
j.err = ErrTimeFormat
return j
}
// save atTime start as duration from midnight
j.atTime = time.Duration(hour)*time.Hour + time.Duration(min)*time.Minute + time.Duration(sec)*time.Second
return j
}
// GetAt returns the specific time of day the job will run at
// s.Every(1).Day().At("10:30").GetAt() == "10:30"
func (j *Job) GetAt() string {
return fmt.Sprintf("%d:%d", j.atTime/time.Hour, (j.atTime%time.Hour)/time.Minute)
}
// Loc sets the location for which to interpret "At"
// s.Every(1).Day().At("10:30").Loc(time.UTC).Do(task)
func (j *Job) Loc(loc *time.Location) *Job {
j.loc = loc
return j
}
// Tag allows you to add labels to a job
// they don't impact the functionality of the job.
func (j *Job) Tag(t string, others ...string) {
j.tags = append(j.tags, t)
for _, tag := range others {
j.tags = append(j.tags, tag)
}
}
// Untag removes a tag from a job
func (j *Job) Untag(t string) {
newTags := []string{}
for _, tag := range j.tags {
if t != tag {
newTags = append(newTags, tag)
}
}
j.tags = newTags
}
// Tags returns the tags attached to the job
func (j *Job) Tags() []string {
return j.tags
}
func (j *Job) periodDuration() (time.Duration, error) {
interval := time.Duration(j.interval)
var periodDuration time.Duration
switch j.unit {
case seconds:
periodDuration = interval * time.Second
case minutes:
periodDuration = interval * time.Minute
case hours:
periodDuration = interval * time.Hour
case days:
periodDuration = interval * time.Hour * 24
case weeks:
periodDuration = interval * time.Hour * 24 * 7
default:
return 0, ErrPeriodNotSpecified
}
return periodDuration, nil
}
// roundToMidnight truncate time to midnight
func (j *Job) roundToMidnight(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, j.loc)
}
// scheduleNextRun Compute the instant when this job should run next
func (j *Job) scheduleNextRun() error {
now := time.Now()
if j.lastRun == time.Unix(0, 0) {
j.lastRun = now
}
periodDuration, err := j.periodDuration()
if err != nil {
return err
}
switch j.unit {
case seconds, minutes, hours:
j.nextRun = j.lastRun.Add(periodDuration)
case days:
j.nextRun = j.roundToMidnight(j.lastRun)
j.nextRun = j.nextRun.Add(j.atTime)
case weeks:
j.nextRun = j.roundToMidnight(j.lastRun)
dayDiff := int(j.startDay)
dayDiff -= int(j.nextRun.Weekday())
if dayDiff != 0 {
j.nextRun = j.nextRun.Add(time.Duration(dayDiff) * 24 * time.Hour)
}
j.nextRun = j.nextRun.Add(j.atTime)
}
// advance to next possible schedule
for j.nextRun.Before(now) || j.nextRun.Before(j.lastRun) {
j.nextRun = j.nextRun.Add(periodDuration)
}
return nil
}
// NextScheduledTime returns the time of when this job is to run next
func (j *Job) NextScheduledTime() time.Time {
return j.nextRun
}
// set the job's unit with seconds,minutes,hours...
func (j *Job) mustInterval(i uint64) error {
if j.interval != i {
return fmt.Errorf("interval must be %d", i)
}
return nil
}
// From schedules the next run of the job
func (j *Job) From(t *time.Time) *Job {
j.nextRun = *t
return j
}
// setUnit sets unit type
func (j *Job) setUnit(unit timeUnit) *Job {
j.unit = unit
return j
}
// Seconds set the unit with seconds
func (j *Job) Seconds() *Job {
return j.setUnit(seconds)
}
// Minutes set the unit with minute
func (j *Job) Minutes() *Job {
return j.setUnit(minutes)
}
// Hours set the unit with hours
func (j *Job) Hours() *Job {
return j.setUnit(hours)
}
// Days set the job's unit with days
func (j *Job) Days() *Job {
return j.setUnit(days)
}
// Weeks sets the units as weeks
func (j *Job) Weeks() *Job {
return j.setUnit(weeks)
}
// Second sets the unit with second
func (j *Job) Second() *Job {
j.mustInterval(1)
return j.Seconds()
}
// Minute sets the unit with minute, which interval is 1
func (j *Job) Minute() *Job {
j.mustInterval(1)
return j.Minutes()
}
// Hour sets the unit with hour, which interval is 1
func (j *Job) Hour() *Job {
j.mustInterval(1)
return j.Hours()
}
// Day sets the job's unit with day, which interval is 1
func (j *Job) Day() *Job {
j.mustInterval(1)
return j.Days()
}
// Week sets the job's unit with week, which interval is 1
func (j *Job) Week() *Job {
j.mustInterval(1)
return j.Weeks()
}
// Weekday start job on specific Weekday
func (j *Job) Weekday(startDay time.Weekday) *Job {
j.mustInterval(1)
j.startDay = startDay
return j.Weeks()
}
// GetWeekday returns which day of the week the job will run on
// This should only be used when .Weekday(...) was called on the job.
func (j *Job) GetWeekday() time.Weekday {
return j.startDay
}
// Monday set the start day with Monday
// - s.Every(1).Monday().Do(task)
func (j *Job) Monday() (job *Job) {
return j.Weekday(time.Monday)
}
// Tuesday sets the job start day Tuesday
func (j *Job) Tuesday() *Job {
return j.Weekday(time.Tuesday)
}
// Wednesday sets the job start day Wednesday
func (j *Job) Wednesday() *Job {
return j.Weekday(time.Wednesday)
}
// Thursday sets the job start day Thursday
func (j *Job) Thursday() *Job {
return j.Weekday(time.Thursday)
}
// Friday sets the job start day Friday
func (j *Job) Friday() *Job {
return j.Weekday(time.Friday)
}
// Saturday sets the job start day Saturday
func (j *Job) Saturday() *Job {
return j.Weekday(time.Saturday)
}
// Sunday sets the job start day Sunday
func (j *Job) Sunday() *Job {
return j.Weekday(time.Sunday)
}
// Lock prevents job to run from multiple instances of gocron
func (j *Job) Lock() *Job {
j.lock = true
return j
}