forked from carlescere/scheduler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.go
327 lines (293 loc) · 6.9 KB
/
scheduler.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
// Package scheduler is a cron replacement based on:
// http://adam.herokuapp.com/past/2010/4/13/rethinking_cron/
// and
// https://github.com/dbader/schedule
//
// Uses include:
// func main() {
// job := func() {
// fmt.Println("Time's up!")
// }
// scheduler.Every(5).Seconds().Run(function)
// scheduler.Every().Day().Run(function)
// scheduler.Every().Sunday().At("08:30").Run(function)
// }
package scheduler
import (
"errors"
"strconv"
"strings"
"sync"
"time"
)
type scheduled interface {
nextRun() (time.Duration, error)
}
// Job defines a running job and allows to stop a scheduled job or run it.
type Job struct {
fn func()
Quit chan bool
SkipWait chan bool
err error
schedule scheduled
isRunning bool
sync.RWMutex
}
type recurrent struct {
units int
period time.Duration
done bool
}
func (r *recurrent) nextRun() (time.Duration, error) {
if r.units == 0 || r.period == 0 {
return 0, errors.New("cannot set recurrent time with 0")
}
if !r.done {
r.done = true
return 0, nil
}
return time.Duration(r.units) * r.period, nil
}
type daily struct {
hour int
min int
sec int
}
func (d *daily) setTime(h, m, s int) {
d.hour = h
d.min = m
d.sec = s
}
func (d daily) nextRun() (time.Duration, error) {
now := time.Now()
year, month, day := now.Date()
date := time.Date(year, month, day, d.hour, d.min, d.sec, 0, time.Local)
if now.Before(date) {
return date.Sub(now), nil
}
date = time.Date(year, month, day+1, d.hour, d.min, d.sec, 0, time.Local)
return date.Sub(now), nil
}
type weekly struct {
day time.Weekday
d daily
}
func (w weekly) nextRun() (time.Duration, error) {
now := time.Now()
year, month, day := now.Date()
numDays := w.day - now.Weekday()
if numDays == 0 {
numDays = 7
} else if numDays < 0 {
numDays += 7
}
date := time.Date(year, month, day+int(numDays), w.d.hour, w.d.min, w.d.sec, 0, time.Local)
return date.Sub(now), nil
}
// Every defines when to run a job. For a recurrent jobs (n seconds/minutes/hours) you
// should specify the unit and then call to the correspondent period method.
func Every(times ...int) *Job {
switch len(times) {
case 0:
return &Job{}
case 1:
r := new(recurrent)
r.units = times[0]
return &Job{schedule: r}
default:
// Yeah... I don't like it either. But go does not support default
// parameters nor method overloading. In an ideal world should
// return an error at compile time not at runtime. :/
return &Job{err: errors.New("too many arguments in Every")}
}
}
// NotImmediately allows recurrent jobs not to be executed immediatelly after
// definition. If a job is declared hourly won't start executing until the first hour
// passed.
func (j *Job) NotImmediately() *Job {
rj, ok := j.schedule.(*recurrent)
if !ok {
j.err = errors.New("bad function chaining")
return j
}
rj.done = true
return j
}
// At lets you define a specific time when the job would be run. Does not work with
// recurrent jobs.
// Time should be defined as a string separated by a colon. Could be used as "08:35:30",
// "08:35" or "8" for only the hours.
func (j *Job) At(hourTime string) *Job {
if j.err != nil {
return j
}
hour, min, sec, err := parseTime(hourTime)
if err != nil {
j.err = err
return j
}
d, ok := j.schedule.(daily)
if !ok {
w, ok := j.schedule.(weekly)
if !ok {
j.err = errors.New("bad function chaining")
return j
}
w.d.setTime(hour, min, sec)
j.schedule = w
} else {
d.setTime(hour, min, sec)
j.schedule = d
}
return j
}
// Run sets the job to the schedule and returns the pointer to the job so it may be
// stopped or executed without waiting or an error.
func (j *Job) Run(f func()) (*Job, error) {
if j.err != nil {
return nil, j.err
}
var next time.Duration
var err error
j.Quit = make(chan bool, 1)
j.SkipWait = make(chan bool, 1)
j.fn = f
// Check for possible errors in scheduling
next, err = j.schedule.nextRun()
if err != nil {
return nil, err
}
go func(j *Job) {
for {
select {
case <-j.Quit:
return
case <-j.SkipWait:
go runJob(j)
case <-time.After(next):
go runJob(j)
}
next, _ = j.schedule.nextRun()
}
}(j)
return j, nil
}
func (j *Job) setRunning(running bool) {
j.Lock()
defer j.Unlock()
j.isRunning = running
}
func runJob(job *Job) {
if job.IsRunning() {
return
}
job.setRunning(true)
job.fn()
job.setRunning(false)
}
func parseTime(str string) (hour, min, sec int, err error) {
chunks := strings.Split(str, ":")
var hourStr, minStr, secStr string
switch len(chunks) {
case 1:
hourStr = chunks[0]
minStr = "0"
secStr = "0"
case 2:
hourStr = chunks[0]
minStr = chunks[1]
secStr = "0"
case 3:
hourStr = chunks[0]
minStr = chunks[1]
secStr = chunks[2]
}
hour, err = strconv.Atoi(hourStr)
if err != nil {
return 0, 0, 0, errors.New("bad time")
}
min, err = strconv.Atoi(minStr)
if err != nil {
return 0, 0, 0, errors.New("bad time")
}
sec, err = strconv.Atoi(secStr)
if err != nil {
return 0, 0, 0, errors.New("bad time")
}
if hour > 23 || min > 59 || sec > 59 {
return 0, 0, 0, errors.New("bad time")
}
return
}
func (j *Job) dayOfWeek(d time.Weekday) *Job {
if j.schedule != nil {
j.err = errors.New("bad function chaining")
}
j.schedule = weekly{day: d}
return j
}
// Monday sets the job to run every Monday.
func (j *Job) Monday() *Job {
return j.dayOfWeek(time.Monday)
}
// Tuesday sets the job to run every Tuesday.
func (j *Job) Tuesday() *Job {
return j.dayOfWeek(time.Tuesday)
}
// Wednesday sets the job to run every Wednesday.
func (j *Job) Wednesday() *Job {
return j.dayOfWeek(time.Wednesday)
}
// Thursday sets the job to run every Thursday.
func (j *Job) Thursday() *Job {
return j.dayOfWeek(time.Thursday)
}
// Friday sets the job to run every Friday.
func (j *Job) Friday() *Job {
return j.dayOfWeek(time.Friday)
}
// Saturday sets the job to run every Saturday.
func (j *Job) Saturday() *Job {
return j.dayOfWeek(time.Saturday)
}
// Sunday sets the job to run every Sunday.
func (j *Job) Sunday() *Job {
return j.dayOfWeek(time.Sunday)
}
// Day sets the job to run every day.
func (j *Job) Day() *Job {
if j.schedule != nil {
j.err = errors.New("bad function chaining")
}
j.schedule = daily{}
return j
}
func (j *Job) timeOfDay(d time.Duration) *Job {
if j.err != nil {
return j
}
r := j.schedule.(*recurrent)
r.period = d
j.schedule = r
return j
}
// Seconds sets the job to run every n Seconds where n was defined in the Every
// function.
func (j *Job) Seconds() *Job {
return j.timeOfDay(time.Second)
}
// Minutes sets the job to run every n Minutes where n was defined in the Every
// function.
func (j *Job) Minutes() *Job {
return j.timeOfDay(time.Minute)
}
// Hours sets the job to run every n Hours where n was defined in the Every function.
func (j *Job) Hours() *Job {
return j.timeOfDay(time.Hour)
}
// IsRunning returns if the job is currently running
func (j *Job) IsRunning() bool {
j.RLock()
defer j.RUnlock()
return j.isRunning
}