-
Notifications
You must be signed in to change notification settings - Fork 4
/
cron.coffee
447 lines (388 loc) · 13.4 KB
/
cron.coffee
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
module.exports = (env) ->
# ##Dependencies
# * node.js imports.
spawn = require("child_process").spawn
util = require 'util'
Promise = env.require 'bluebird'
assert = env.require 'cassert'
M = env.matcher
# * `node-chrono` Parses the dates for the `notifyWhen` function.
chrono = require 'chrono-node'
# * `node-cron`: Triggers the time events.
CronJob = env.CronJob or require('cron').CronJob
milliseconds = env.require './lib/milliseconds'
# ##The CronPlugin
class CronPlugin extends env.plugins.Plugin
# The `init` function just registers the clock actuator.
init: (app, @framework, @config) =>
@framework.ruleManager.addPredicateProvider(new CronPredicateProvider(@framework, @config))
@framework.ruleManager.addPredicateProvider(new EveryCronPredicateProvider(@framework, @config))
plugin = new CronPlugin()
# ##The PredicateProvider
# Provides the time and time events for the rule module.
class CronPredicateProvider extends env.predicates.PredicateProvider
presets: [
{
name: "time"
input: "its 8:00"
},
{
name: "before/after time"
input: "its after 8:00"
}
]
constructor: (@framework, @config) ->
env.logger.info "the time is: #{@getTime()}"
return
getTime: -> new Date()
parsePredicate: (input, context) ->
modifier = null
parseDateResults = null
dateMatch = null
dateDetected = no
dateString = null
fullMatch = null
nextInput = null
exprTokens = null
theTime = @getTime()
onDateStringMatch = ( (m, match) =>
possibleDateString = match.trim()
parseDateResults = chrono.parse(possibleDateString, theTime)
if parseDateResults.length > 0 and parseDateResults[0].index is 0
dateDetected = yes
fullMatch = m.getFullMatch()
dateString = possibleDateString
nextInput = m.getRemainingInput()
return m
)
onDateStringExprMatch = ( (m, tokens) =>
exprTokens = tokens
dateDetected = yes
fullMatch = m.getFullMatch()
nextInput = m.getRemainingInput()
return m
)
hadPrefix = false
M(input, context)
.match(
['its ', 'it is '],
optional: yes, type: 'static',
(m, match) => hadPrefix = yes
)
.match(
['before ', 'after '],
param: 'modifier', type: 'select', optional: yes,
(m, match) => modifier = match.trim(); hadPrefix = yes
)
.or([
( (m) =>
m.match(
/^(.+?)($| for .*| and .*| or .*|\).*|\].*)/,
param: 'time', type: 'time',
onDateStringMatch
)
),
( (m) =>
if hadPrefix then m.matchStringWithVars(onDateStringExprMatch)
else M(null, context)
),
( (m) =>
if hadPrefix then m.matchVariable( (m, v) => onDateStringExprMatch(m, [v]) )
else M(null, context)
)
])
if dateDetected
if dateString?
if parseDateResults.length is 0
context?.addError("Could not parse date: \"#{dateMatch}\"")
return null
else if parseDateResults.length > 1
context?.addError("Multiple dates given: \"#{dateMatch}\"")
return null
parseResult = parseDateResults[0]
if modifier in ['after', 'before'] and parseResult.end?
context?.addError("You can't give a date range when using \"#{modifier}\"")
unless modifier?
if parseResult.end?
modifier = 'range'
else
modifier = 'exact'
else
assert Array.isArray exprTokens
unless modifier?
modifier = 'exact'
assert fullMatch?
assert nextInput?
return {
token: fullMatch
nextInput: nextInput
predicateHandler: (
if dateString? then new StringCronPredicateHandler(this, modifier, dateString)
else new ExprCronPredicateHandler(this, modifier, exprTokens)
)
}
else return null
class BaseCronPredicateHandler extends env.predicates.PredicateHandler
constructor: (@provider, @modifier) -> #nop
_createJobs: (dateString) ->
parseResult = @_reparseDateString(dateString)
unless parseResult?
throw new Error("\"#{dateString}\" is not a valid date or time.")
{second, minute, hour, day, month, dayOfWeek} = @_parseDateToCronFormat(parseResult.start)
@jobs = []
switch @modifier
when 'exact'
@jobs.push new CronJob(
cronTime: "#{second} #{minute} #{hour} #{day} #{month} #{dayOfWeek}"
onTick: => @emit "change", 'event'
start: false
)
when 'before'
###
before means same day but before the time so the cronjob must trigger at 0:00
###
@jobs.push new CronJob(
cronTime: "0 0 0 #{day} #{month} #{dayOfWeek}"
onTick: => @emit "change", true
start: false
)
# and the predicate gets false at the given time
@jobs.push new CronJob(
cronTime: "#{second} #{minute} #{hour} #{day} #{month} #{dayOfWeek}"
onTick: => @emit "change", false
start: false
)
when 'after'
# predicate gets true at the given time
@jobs.push new CronJob(
cronTime: "#{second} #{minute} #{hour} #{day} #{month} #{dayOfWeek}"
onTick: => @emit "change", true
start: false
)
# and false at the end of the day
@jobs.push new CronJob(
cronTime: "59 59 23 #{day} #{month} #{dayOfWeek}"
onTick: => @emit "change", false
start: false
)
when 'range'
# predicate gets true at the given time
@jobs.push new CronJob(
cronTime: "#{second} #{minute} #{hour} #{day} #{month} #{dayOfWeek}"
onTick: => @emit "change", true
start: false
)
# and gets false at the end time
{second, minute, hour, day, month, dayOfWeek} = @_parseDateToCronFormat(parseResult.end)
@jobs.push new CronJob(
cronTime: "#{second} #{minute} #{hour} #{day} #{month} #{dayOfWeek}"
onTick: => @emit "change", false
start: false
)
else assert false
_setup: (dateString) ->
@_createJobs(dateString)
job.start() for job in @jobs
getType: -> if @modifier is 'exact' then 'event' else 'state'
_reparseDateString: (dateString) ->
theTime = @provider.getTime()
return chrono.parse(dateString, theTime)[0]
_getValue: (dateString)->
parseResult = @_reparseDateString(dateString)
unless parseResult?
throw new Error("\"#{dateString}\" is not a valid date or time.")
now = parseResult.referenceDate
start = parseResult.startDate
end = parseResult.endDate
unless parseResult.start.hour?
start.setHours now.getHours()
unless parseResult.start.minute?
start.setMinutes now.getMinutes()
unless parseResult.start.second?
start.setSeconds now.getSeconds()
if 'year' in parseResult.start.impliedComponents
start.setFullYear now.getFullYear()
if 'month' in parseResult.start.impliedComponents
start.setMonth now.getMonth()
if 'day' in parseResult.start.impliedComponents
start.setDate now.getDate()
if @modifier is 'exact'
start.setMilliseconds now.getMilliseconds()
if parseResult.start.dayOfWeek?
if parseResult.start.dayOfWeek isnt now.getDay()
return Promise.resolve(false)
# console.log "now: ", now
# console.log "start: ", start
# console.log "end: ", end
return Promise.resolve(
switch @modifier
when 'exact' then start >= now and start <= now # start == now does not work!
when 'after' then now >= start
when 'before' then now <= start
when 'range' then start <= now <= end
else assert false
)
# Removes the notification for an with `notifyWhen` registered predicate.
_destroy: ->
if @jobs?
for cj in @jobs
cj.stop()
# Convert a parsedDate to a cronjob-syntax like object. The parsedDate must be parsed from
# [chrono-node](https://github.com/berryboy/chrono). For Exampe converts the parsedDate of
# `"12:00"` to:
#
# {
# second: 0
# minute: 0
# hour: 12
# day: "*"
# month: "*"
# dayOfWeek: "*"
# }
#
# or `"Monday"` gets:
#
# {
# second: 0
# minute: 0
# hour: 0
# day: "*"
# month: "*"
# dayOfWeek: 1
# }
_parseDateToCronFormat: (date) ->
second = date.second
minute = date.minute
hour = date.hour
#console.log date
if not second? and not minute? and not hour
second = 0
minute = 0
hour = 0
else
if not second?
second = "*"
if not minute?
minute = "*"
if not hour?
hour = "*"
if date.impliedComponents?
month = if 'month' in date.impliedComponents then "*" else date.month
day = if 'day' in date.impliedComponents then "*" else date.day
dayOfWeek = if date.dayOfWeek? then date.dayOfWeek else "*"
return {
second: second
minute: minute
hour: hour
day: day
month: month
dayOfWeek: dayOfWeek
}
class StringCronPredicateHandler extends BaseCronPredicateHandler
constructor: (provider, modifier, @dateString) ->
super(provider, modifier)
setup: ->
@_setup(@dateString)
super()
destroy: ->
@_destroy()
super()
getValue: -> @_getValue(@dateString)
class ExprCronPredicateHandler extends BaseCronPredicateHandler
constructor: (provider, modifier, @exprTokens) ->
super(provider, modifier)
@_variableManager = @provider.framework.variableManager
_setupJobs: ->
@_variableManager.evaluateStringExpression(@exprTokens).then( (dateString) =>
if @destroyed then return
@_setup("#{dateString}")
).catch( (error) ->
env.logger.error("Error creating cron predicate handler: #{error.message}")
env.logger.debug(error.stack)
)
setup: ->
@destroyed = no
@_setupJobs()
@_variableManager.notifyOnChange(@exprTokens, @expChangeListener = () =>
@_destroy()
@_setupJobs()
)
super()
getValue: ->
return @_variableManager.evaluateStringExpression(@exprTokens).then( (dateString) =>
return @_getValue("#{dateString}")
)
destroy: ->
@_variableManager.cancelNotifyOnChange(@expChangeListener)
@destroyed = yes
super()
# ##The EveryPredicateProvider
# Provides every x minutes/hours/... predicates.
class EveryCronPredicateProvider extends env.predicates.PredicateProvider
constructor: (@framework, @config) ->
super()
parsePredicate: (input, context) ->
exprTokens = null
fullMatch = null
nextInput = null
matchingUnit = null
M(input, context)
.match('every ')
.matchTimeDurationExpression( (m, {tokens, unit}) =>
exprTokens = tokens
matchingUnit = unit
fullMatch = m.getFullMatch()
nextInput = m.getRemainingInput()
)
if fullMatch?
assert matchingUnit?
assert exprTokens?
return {
token: fullMatch
nextInput: nextInput
predicateHandler: new EveryCronPredicateHandler(@framework, exprTokens, matchingUnit)
}
else return null
class EveryCronPredicateHandler extends env.predicates.PredicateHandler
constructor: (framework, @exprTokens, @unit) ->
super()
@_variableManager = framework.variableManager
setup: ->
@_setupTimeout()
# change the timeout if the expr changes:
@_variableManager.notifyOnChange(@exprTokens, @expChangeListener = () =>
@_lastTime = null
@_setupTimeout()
)
super()
_setupTimeout: ->
@destroyed = no
@_variableManager.evaluateStringExpression(@exprTokens).then( (time) =>
if @destroyed then return
timeMs = milliseconds.parse "#{time} #{@unit}"
now = new Date().getTime()
unless @_lastTime?
# aways ececute on full minutes, etc...
@_lastTime = now - (now % timeMs)
timeDiff = (@_lastTime + timeMs) - now
timeDiff = 0 if timeDiff < 0
clearTimeout(@_timeout)
@_timeout = setTimeout( ( =>
@emit "change", 'event'
@_lastTime += timeMs
@_setupTimeout()
), timeDiff)
).catch( (error) ->
env.logger.error("Error creating cron predicate handler: #{error.message}")
env.logger.debug(error.stack)
)
getValue: -> Promise.resolve false
getType: -> 'event'
destroy: ->
if @expChangeListener?
clearTimeout(@_timeout)
@_variableManager.cancelNotifyOnChange(@expChangeListener)
@expChangeListener = null
@destroyed = yes
super()
return plugin