-
Notifications
You must be signed in to change notification settings - Fork 0
/
cronjob.go
325 lines (268 loc) · 6.36 KB
/
cronjob.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
package cronjob
import (
"context"
"log"
"os"
"sync"
"sync/atomic"
"time"
)
type CronJob struct {
scheduler Scheduler
logger *log.Logger
verbose bool
idCount int
location *time.Location
add chan *Node
remove chan int
stop chan struct{}
nodes chan chan []*Node
runningMu sync.Mutex
isRunning bool
}
type Schedule interface {
// Calculate calculates the duartion till the next activation time.
Calculate(time.Time) time.Duration
}
type CyclicSchedule interface {
// MoveNextAvtivation re-calculates the next time the schedule will be activated
// at.
MoveNextAvtivation(time.Time)
Schedule
}
type Scheduler interface {
// NextCycle returns the duration to sleep before next activation cycle.
NextCycle(time.Time) time.Duration
// RunNow returns the jobs that need to be ran now and cleans the scheduler.
RunNow(time.Time) []*Node
// GetAll returns all the nodes in the scheduler.
GetAll() []*Node
// AddNode adds a new node to the scheduler.
AddNode(time.Time, *Node)
// RemoveNode removes node with id provided.
RemoveNode(int)
// Clean removes the node (field) and re-calculates appropriate nodes.
Clean(time.Time, []*Node)
}
type FuncJob func() error
type Job struct {
job FuncJob
chain Chain
runOnStart bool
}
func New(confs ...CronJobConf) *CronJob {
cronJob := &CronJob{
scheduler: &linkedList{},
logger: log.New(os.Stdout, "[CronJob]", log.Flags()),
location: time.Local,
add: make(chan *Node),
remove: make(chan int),
stop: make(chan struct{}),
nodes: make(chan chan []*Node),
}
for _, conf := range confs {
conf(cronJob)
}
return cronJob
}
// Now returns the current time in the location used by the instance.
func (c *CronJob) Now() time.Time {
return time.Now().In(c.location)
}
// AddFunc adds the function: cmd (field) to the execution cycle.
//
// can be called after starting the execution cycle or before.
//
// (*CronJob).AddFunc(foo, cronjob.In(time.Now(), 4 * time.Hour))
//
// will schedule foo to run in 4 hours from time.Now()
func (c *CronJob) AddFunc(cmd FuncJob, schedule Schedule, confs ...JobConf) int {
return c.addJob(&Job{job: cmd}, schedule, confs...)
}
// RemoveJob removes the job with id: id (field). (no-op if job not found)
//
// can be called after starting the execution cycle or before.
func (c *CronJob) RemoveJob(id int) {
c.runningMu.Lock()
defer c.runningMu.Unlock()
if !c.isRunning {
c.scheduler.RemoveNode(id)
} else {
c.remove <- id
}
}
// Location returns the location used by the instance.
func (c *CronJob) Location() *time.Location {
return c.location
}
// Start the processing thread in its own gorutine.
//
// no-op if already running.
func (c *CronJob) Start() {
c.runningMu.Lock()
defer c.runningMu.Unlock()
if c.isRunning {
return
}
c.isRunning = true
go c.run()
}
// Stop stops the cronjobs processing thread.
//
// no-op if not running.
func (c *CronJob) Stop() {
c.runningMu.Lock()
defer c.runningMu.Unlock()
if !c.isRunning {
return
}
c.stop <- struct{}{}
c.isRunning = false
}
// StopWithFlush stops the cronjobs processing thread.
//
// runs all the current jobs and cleans the scheduler.
//
// no-op if not running.
func (c *CronJob) StopWithFlush() context.Context {
c.runningMu.Lock()
if !c.isRunning {
c.runningMu.Unlock()
ctx, cancel := context.WithCancel(context.Background())
cancel()
return ctx
}
c.stop <- struct{}{}
c.isRunning = false
c.runningMu.Unlock()
// run jobs.
nodes := c.Jobs()
ctx, cancel := context.WithCancel(context.Background())
if len(nodes) == 0 { // no nodes.
cancel()
return ctx
}
var runningWorkerCount int64 = int64(len(nodes))
for _, node := range nodes {
go func(node *Node) {
node.Job.Run()
c := atomic.AddInt64(&runningWorkerCount, -1)
if c == 0 { // last job, cancel.
cancel()
}
}(node)
}
// clean nodes.
c.scheduler.Clean(c.Now(), nodes)
return ctx
}
// Start the processing thread.
//
// no-op if already running.
func (c *CronJob) Run() {
c.runningMu.Lock()
if c.isRunning {
return
}
c.isRunning = true
c.runningMu.Unlock()
c.run()
}
// Jobs returns the current nodes which are registered to the scheduler.
func (c *CronJob) Jobs() []*Node {
c.runningMu.Lock()
defer c.runningMu.Unlock()
if c.isRunning {
replyChan := make(chan []*Node, 1)
c.nodes <- replyChan
return <-replyChan
} else {
return c.scheduler.GetAll()
}
}
func (c *CronJob) addJob(job *Job, schedule Schedule, confs ...JobConf) int {
c.runningMu.Lock()
defer c.runningMu.Unlock()
for _, conf := range confs {
conf(job)
}
// add a job which will be ran on the first execution cycle (negative time.Duration).
if job.runOnStart {
node := &Node{
Schedule: &constantSchedule{c.Now().Add(-1 * time.Second)},
Job: job,
}
if c.isRunning {
go job.Run()
} else {
c.idCount++
node.Id = c.idCount
c.scheduler.AddNode(c.Now(), node)
}
}
c.idCount++
node := &Node{
Id: c.idCount,
Schedule: schedule,
Job: job,
}
if c.isRunning {
c.add <- node
} else {
c.scheduler.AddNode(c.Now(), node)
}
return node.Id
}
func (c *CronJob) run() {
c.logger.Println("starting processing thread")
now := c.Now()
for {
var timer *time.Timer
if sleep := c.scheduler.NextCycle(now); sleep >= 0 {
timer = time.NewTimer(sleep)
} else {
timer = time.NewTimer(1000000 * time.Hour)
}
for {
select {
case woke := <-timer.C:
now = woke.In(c.location)
// run all jobs.
nodes := c.scheduler.RunNow(now)
for _, node := range nodes {
go node.Job.Run()
}
// clean nodes after running.
c.scheduler.Clean(now, nodes)
c.logDebugf("woke up at: %v\n", woke)
case reply := <-c.nodes:
reply <- c.scheduler.GetAll()
continue // no need to re-calc timer.
case node := <-c.add:
timer.Stop()
now = c.Now()
c.scheduler.AddNode(now, node)
c.logDebugf("added new node with id: %v\n", node.Id)
case id := <-c.remove:
timer.Stop()
now = c.Now()
c.scheduler.RemoveNode(id)
c.logDebugf("attempting to remove node with id: %v\n", id)
case <-c.stop:
timer.Stop()
c.logger.Println("exiticing processing thread")
return
}
break
}
}
}
func (c *CronJob) logDebugf(format string, v ...interface{}) {
if c.verbose {
c.logger.Printf(format, v...)
}
}
// Run runs the function provided to job with the chains.
func (j *Job) Run() {
j.chain.Run(j.job)
}