forked from go-co-op/gocron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.go
270 lines (229 loc) · 6.89 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
package gocron
import (
"context"
"fmt"
"sync"
"time"
"github.com/robfig/cron/v3"
"golang.org/x/sync/singleflight"
)
// Job struct stores the information necessary to run a Job
type Job struct {
sync.RWMutex
jobFunction
interval int // pause interval * unit between runs
duration time.Duration // time duration between runs
unit schedulingUnit // time units, ,e.g. 'minutes', 'hours'...
startsImmediately bool // if the Job should run upon scheduler start
atTime time.Duration // optional time at which this Job runs when interval is day
startAtTime time.Time // optional time at which the Job starts
error error // error related to Job
lastRun time.Time // datetime of last run
nextRun time.Time // datetime of next run
scheduledWeekday []time.Weekday // Specific days of the week to start on
dayOfTheMonth int // Specific day of the month to run the job
tags []string // allow the user to tag Jobs with certain labels
runCount int // number of times the job ran
timer *time.Timer // handles running tasks at specific time
cronSchedule cron.Schedule // stores the schedule when a task uses cron
}
type jobFunction struct {
function interface{} // task's function
parameters []interface{} // task's function parameters
name string //nolint the function name to run
runConfig runConfig // configuration for how many times to run the job
limiter *singleflight.Group // limits inflight runs of job to one
ctx context.Context // for cancellation
cancel context.CancelFunc // for cancellation
}
type runConfig struct {
finiteRuns bool
maxRuns int
mode mode
}
// mode is the Job's running mode
type mode int8
const (
// defaultMode disable any mode
defaultMode mode = iota
// singletonMode switch to single job mode
singletonMode
)
// newJob creates a new Job with the provided interval
func newJob(interval int, startImmediately bool) *Job {
ctx, cancel := context.WithCancel(context.Background())
return &Job{
interval: interval,
unit: Seconds,
lastRun: time.Time{},
nextRun: time.Time{},
jobFunction: jobFunction{
ctx: ctx,
cancel: cancel,
},
tags: []string{},
startsImmediately: startImmediately,
}
}
func (j *Job) neverRan() bool {
return j.lastRun.IsZero()
}
func (j *Job) getStartsImmediately() bool {
return j.startsImmediately
}
func (j *Job) setStartsImmediately(b bool) {
j.startsImmediately = b
}
func (j *Job) setTimer(t *time.Timer) {
j.Lock()
defer j.Unlock()
j.timer = t
}
func (j *Job) getAtTime() time.Duration {
return j.atTime
}
func (j *Job) setAtTime(t time.Duration) {
j.atTime = t
}
func (j *Job) getStartAtTime() time.Time {
return j.startAtTime
}
func (j *Job) setStartAtTime(t time.Time) {
j.startAtTime = t
}
func (j *Job) getUnit() schedulingUnit {
j.RLock()
defer j.RUnlock()
return j.unit
}
func (j *Job) setUnit(t schedulingUnit) {
j.Lock()
defer j.Unlock()
j.unit = t
}
func (j *Job) getDuration() time.Duration {
j.RLock()
defer j.RUnlock()
return j.duration
}
func (j *Job) setDuration(t time.Duration) {
j.Lock()
defer j.Unlock()
j.duration = t
}
// Error returns an error if one occurred while creating the Job.
// If multiple errors occurred, they will be wrapped and can be
// checked using the standard unwrap options.
func (j *Job) Error() error {
return j.error
}
// Tag allows you to add arbitrary labels to a Job that do not
// impact the functionality of the Job
func (j *Job) Tag(tags ...string) {
j.tags = append(j.tags, tags...)
}
// Untag removes a tag from a Job
func (j *Job) Untag(t string) {
var 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
}
// ScheduledTime returns the time of the Job's next scheduled run
func (j *Job) ScheduledTime() time.Time {
j.RLock()
defer j.RUnlock()
return j.nextRun
}
// ScheduledAtTime returns the specific time of day the Job will run at
func (j *Job) ScheduledAtTime() string {
return fmt.Sprintf("%d:%d", j.atTime/time.Hour, (j.atTime%time.Hour)/time.Minute)
}
// Weekday returns which day of the week the Job will run on and
// will return an error if the Job is not scheduled weekly
func (j *Job) Weekday() (time.Weekday, error) {
if len(j.scheduledWeekday) == 0 {
return time.Sunday, ErrNotScheduledWeekday
}
return j.scheduledWeekday[0], nil
}
// Weekdays returns a slice of time.Weekday that the Job will run in a week and
// will return an error if the Job is not scheduled weekly
func (j *Job) Weekdays() []time.Weekday {
// appending on j.scheduledWeekday may cause a side effect
if len(j.scheduledWeekday) == 0 {
return []time.Weekday{time.Sunday}
}
return j.scheduledWeekday
}
// return j.scheduledWeekday
// }
// LimitRunsTo limits the number of executions of this job to n.
// The job will remain in the scheduler.
// Note: If a job is added to a running scheduler and this method is then used
// you may see the job run more than the set limit as job is scheduled immediately
// by default upon being added to the scheduler. It is recommended to use the
// LimitRunsTo() func on the scheduler chain when scheduling the job.
// For example: scheduler.LimitRunsTo(1).Do()
func (j *Job) LimitRunsTo(n int) {
j.Lock()
defer j.Unlock()
j.runConfig.finiteRuns = true
j.runConfig.maxRuns = n
}
// SingletonMode prevents a new job from starting if the prior job has not yet
// completed it's run
// Note: If a job is added to a running scheduler and this method is then used
// you may see the job run overrun itself as job is scheduled immediately
// by default upon being added to the scheduler. It is recommended to use the
// SingletonMode() func on the scheduler chain when scheduling the job.
func (j *Job) SingletonMode() {
j.Lock()
defer j.Unlock()
j.runConfig.mode = singletonMode
j.jobFunction.limiter = &singleflight.Group{}
}
// shouldRun evaluates if this job should run again
// based on the runConfig
func (j *Job) shouldRun() bool {
j.RLock()
defer j.RUnlock()
return !j.runConfig.finiteRuns || j.runCount < j.runConfig.maxRuns
}
// LastRun returns the time the job was run last
func (j *Job) LastRun() time.Time {
return j.lastRun
}
func (j *Job) setLastRun(t time.Time) {
j.lastRun = t
}
// NextRun returns the time the job will run next
func (j *Job) NextRun() time.Time {
j.RLock()
defer j.RUnlock()
return j.nextRun
}
func (j *Job) setNextRun(t time.Time) {
j.Lock()
defer j.Unlock()
j.nextRun = t
}
// RunCount returns the number of time the job ran so far
func (j *Job) RunCount() int {
return j.runCount
}
func (j *Job) stop() {
j.Lock()
defer j.Unlock()
if j.timer != nil {
j.timer.Stop()
}
j.cancel()
}