-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.go
347 lines (295 loc) · 8.91 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright (c) 2019,CAO HONGJU. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
//
// Copyright (C) 2012 Rob Figueiredo (github.com/robfig/cron)
// All Rights Reserved.
//
// MIT LICENSE
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package scheduler
import (
"container/heap"
"context"
"errors"
"fmt"
"os"
"sync"
"sync/atomic"
"time"
"github.com/cnotch/scheduler/cron"
)
const (
minInterval = time.Millisecond // minimum trigger interval
)
// PanicHandler is to handle panic caused by an asynchronous job.
type PanicHandler func(job *ManagedJob, r interface{})
// A Scheduler maintains a registry of Jobs.
// Once registered, the Scheduler is responsible for executing Jobs
// when their scheduled time arrives.
type Scheduler struct {
count int64
wg *sync.WaitGroup
add chan *ManagedJob
remove chan *ManagedJob
snapshot chan chan []*ManagedJob
panicHandler atomic.Value
loc *time.Location
ctx context.Context
cancel context.CancelFunc
terminated bool
}
// New returns a new Scheduler instance.
func New(options ...Option) *Scheduler {
s := &Scheduler{
wg: &sync.WaitGroup{},
add: make(chan *ManagedJob),
remove: make(chan *ManagedJob),
snapshot: make(chan chan []*ManagedJob),
loc: time.Local,
}
for _, option := range options {
option.apply(s)
}
if s.ctx == nil {
s.ctx, s.cancel = context.WithCancel(context.Background())
}
if s.panicHandler.Load() == nil {
s.panicHandler.Store(PanicHandler(defaultPanicHandle))
}
// start
s.wg.Add(1)
go s.run()
return s
}
// AfterFunc posts the function f to the Scheduler.
// The function f will execute after specified delay only once,
// and then remove from the Scheduler.
func (s *Scheduler) AfterFunc(delay time.Duration, f func(), tag interface{}) (*ManagedJob, error) {
return s.After(delay, JobFunc(f), tag)
}
// After posts the job to the Scheduler.
// The job will execute after specified delay only once,
// and then remove from the Scheduler.
func (s *Scheduler) After(delay time.Duration, job Job, tag interface{}) (*ManagedJob, error) {
return s.Post(&afterSchedule{delay: delay}, job, tag)
}
// PeriodFunc posts the function f to the Scheduler.
// The function f will execute the first time at the specified delay,
// followed by a fixed period. If the execution time of f exceeds
// the period, there will be multiple instances of f running at the same time.
func (s *Scheduler) PeriodFunc(initialDelay, period time.Duration, f func(), tag interface{}) (*ManagedJob, error) {
return s.Period(initialDelay, period, JobFunc(f), tag)
}
// Period posts the job to the Scheduler.
// The job will execute the first time at the specified delay,
// followed by a fixed period. If the execution time of job exceeds
// the period, there will be multiple instances of job running at the same time.
func (s *Scheduler) Period(initialDelay, period time.Duration, job Job, tag interface{}) (*ManagedJob, error) {
if period < time.Millisecond {
return nil, errors.New("preiod must not be less than 1ms")
}
return s.Post(&periodSchedule{initialDelay: initialDelay, period: period}, job, tag)
}
// CronFunc posts the function f to the Scheduler, and associate the given cron expression with it.
func (s *Scheduler) CronFunc(cronExpr string, f func(), tag interface{}) (*ManagedJob, error) {
return s.Cron(cronExpr, JobFunc(f), tag)
}
// Cron posts the job to the Scheduler, and associate the given cron expression with it.
func (s *Scheduler) Cron(cronExpr string, job Job, tag interface{}) (*ManagedJob, error) {
cexp, err := cron.Parse(cronExpr)
if err != nil {
return nil, err
}
return s.Post(cexp, job, tag)
}
// PostFunc posts the function f to the Scheduler, and associate the given schedule with it.
func (s *Scheduler) PostFunc(schedule Schedule, f func(), tag interface{}) (*ManagedJob, error) {
return s.Post(schedule, JobFunc(f), tag)
}
// Post posts the job to the Scheduler, and associate the given schedule with it.
func (s *Scheduler) Post(schedule Schedule, job Job, tag interface{}) (mjob *ManagedJob, err error) {
defer func() { // after terminated, add throw panic
if r := recover(); r != nil {
err = errors.New("scheduler is terminated")
}
}()
postTime := s.now()
next := schedule.Next(postTime)
if next.IsZero() {
return nil, errors.New("schedule is empty, never a scheduled time to arrive")
}
j := &ManagedJob{
tag: tag,
schelule: schedule,
job: job,
remove: s.remove,
postTime: postTime,
next: next,
}
j.nextTime.set(j.next)
s.add <- j
return j, nil
}
// Shutdown shutdowns scheduler.
func (s *Scheduler) Shutdown() {
s.cancel()
}
// ShutdownAndWait shutdowns scheduler and wait for all jobs to complete.
func (s *Scheduler) ShutdownAndWait() {
s.cancel()
s.wg.Wait()
}
// Terminated determines that the scheduler has terminated
func (s *Scheduler) Terminated() bool {
return s.terminated
}
// Jobs returns the scheduled jobs.
func (s *Scheduler) Jobs() (jobs []*ManagedJob) {
defer func() {
if r := recover(); r != nil {
jobs = nil // when s.snapshot closed
}
}()
replyChan := make(chan []*ManagedJob, 1)
s.snapshot <- replyChan
jobs = <-replyChan
return
}
// Count returns jobs count.
func (s *Scheduler) Count() int {
l := atomic.LoadInt64(&s.count)
return int(l)
}
// Location returns the time zone location of the scheduler.
func (s *Scheduler) Location() *time.Location {
return s.loc
}
// SetPanicHandler set the panic handler of the scheduler.
func (s *Scheduler) SetPanicHandler(panicHandler PanicHandler) {
if panicHandler == nil {
return
}
s.panicHandler.Store(panicHandler)
}
func (s *Scheduler) run() {
defer s.wg.Done()
jobs := make(jobQueue, 0, 16)
for {
atomic.StoreInt64(&s.count, int64(len(jobs)))
d := time.Duration(100000 * time.Hour) // if there are no jobs
if len(jobs) > 0 {
d = jobs[0].next.Sub(s.now())
if d < 0 {
d = 0
}
}
timer := time.NewTimer(d)
select {
case <-s.ctx.Done(): // exit Scheduler
timer.Stop()
s.internalClose()
return
case now := <-timer.C:
now = now.In(s.loc)
s.runExpiredJobs(now, &jobs)
case newJ := <-s.add:
timer.Stop()
heap.Push(&jobs, newJ)
case removeJ := <-s.remove:
timer.Stop()
s.removeJob(removeJ, &jobs)
case replyChan := <-s.snapshot:
timer.Stop()
snapshotJobs := make([]*ManagedJob, len(jobs))
copy(snapshotJobs, jobs)
replyChan <- snapshotJobs
}
}
}
func (s *Scheduler) runExpiredJobs(now time.Time, jobs *jobQueue) {
for len(*jobs) > 0 {
j := (*jobs)[0]
if j.next.After(now) {
break
}
s.wg.Add(1)
go s.safeRun(j)
next := j.schelule.Next(j.next)
if next.IsZero() {
heap.Pop(jobs)
} else {
jobs.updateNext(j, next)
}
}
}
func (s *Scheduler) safeRun(j *ManagedJob) {
defer func() {
s.wg.Done()
if r := recover(); r != nil {
panicHandler := s.panicHandler.Load().(PanicHandler)
panicHandler(j, r)
}
}()
j.job.Run()
}
func (s *Scheduler) removeJob(removeJ *ManagedJob, jobs *jobQueue) {
if removeJ.index < 0 || removeJ.index >= len(*jobs) {
return
}
if removeJ == (*jobs)[removeJ.index] {
heap.Remove(jobs, removeJ.index)
}
}
func (s *Scheduler) internalClose() {
s.terminated = true
close(s.add)
close(s.remove)
close(s.snapshot)
atomic.StoreInt64(&s.count, 0)
}
func (s *Scheduler) now() time.Time {
return time.Now().In(s.loc)
}
func defaultPanicHandle(job *ManagedJob, r interface{}) {
fmt.Fprintf(os.Stderr, "Tag: %+v\n - %+v\n", job.tag, r)
}
type afterSchedule struct {
called bool
delay time.Duration
}
func (at *afterSchedule) Next(t time.Time) time.Time {
if at.called {
return time.Time{}
}
at.called = true
return t.Add(at.delay)
}
type periodSchedule struct {
called bool
initialDelay, period time.Duration
}
func (pt *periodSchedule) Next(t time.Time) time.Time {
d := pt.initialDelay
if pt.called {
d = pt.period
}
pt.called = true
return t.Add(d)
}