/
cron.js
590 lines (492 loc) · 13.7 KB
/
cron.js
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['moment-timezone'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('moment-timezone'), require('child_process'));
} else {
root.Cron = factory(root.moment);
}
}(this, function (moment, child_process) {
var exports = {},
timeUnits = ['second', 'minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'],
spawn = child_process && child_process.spawn;
function CronTime(source, zone, utcOffset) {
this.source = source;
if (zone) {
if (moment.tz.names().indexOf(zone) === -1) {
throw new Error('Invalid timezone.');
}
this.zone = zone;
}
if (utcOffset) this.utcOffset = utcOffset;
var that = this;
timeUnits.map(function(timeUnit){
that[timeUnit] = {};
});
if (this.source instanceof Date || this.source._isAMomentObject) {
this.source = moment(this.source);
this.realDate = true;
} else {
this._parse();
this._verifyParse();
}
}
CronTime.constraints = [
[0, 59],
[0, 59],
[0, 23],
[1, 31],
[0, 11],
[0, 6]
];
CronTime.monthConstraints = [
31,
29, //support leap year...not perfect
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
CronTime.parseDefaults = ['0', '*', '*', '*', '*', '*'];
CronTime.aliases = {
jan: 0,
feb: 1,
mar: 2,
apr: 3,
may: 4,
jun: 5,
jul: 6,
aug: 7,
sep: 8,
oct: 9,
nov: 10,
dec: 11,
sun: 0,
mon: 1,
tue: 2,
wed: 3,
thu: 4,
fri: 5,
sat: 6
};
CronTime.prototype = {
_verifyParse: function() {
var months = Object.keys(this.month);
for (var i = 0; i < months.length; i++) {
var m = months[i];
var con = CronTime.monthConstraints[parseInt(m, 10)];
var ok = false;
var dsom = Object.keys(this.dayOfMonth);
for (var j = 0; j < dsom.length; j++) {
var dom = dsom[j];
if (dom <= con)
ok = true;
}
if (!ok) {
console.warn('Month \'' + m + '\' is limited to \'' + con + '\' days.');
}
}
},
/**
* calculates the next send time
*/
sendAt: function(i) {
var date = this.realDate ? this.source : moment();
// Set the timezone if given (http://momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone/)
if (this.zone) {
date = date.tz(this.zone);
}
if (this.utcOffset) {
date = date.utcOffset(this.utcOffset);
}
if (this.realDate) {
return date;
}
//add 1 second so next time isn't now (can cause timeout to be 0 or negative number)
var now = new Date();
var targetSecond = date.seconds();
var diff = Math.abs(targetSecond - now.getSeconds())
// there was a problem when `date` is 1424777177999 and `now` is 1424777178000
// 1 ms diff but this is another second...
if ( diff == 0 || (diff == 1 && now.getMilliseconds() <= date.milliseconds() ) ) {
//console.log('add 1 second?');
date = date.add(1, 's');
}
//If the i argument is not given, return the next send time
if (isNaN(i) || i < 0) {
date = this._getNextDateFrom(date);
return date;
} else {
//Else return the next i send times
var dates = [];
for (; i > 0; i--) {
date = this._getNextDateFrom(date);
dates.push(moment(date));
if (i > 1)
date.add(1,'s');
}
return dates;
}
},
/**
* Get the number of milliseconds in the future at which to fire our callbacks.
*/
getTimeout: function() {
return Math.max(-1, this.sendAt() - moment());
},
/**
* writes out a cron string
*/
toString: function() {
return this.toJSON().join(' ');
},
/**
* Json representation of the parsed cron syntax.
*/
toJSON: function() {
var self = this;
return timeUnits.map(function(timeName) {
return self._wcOrAll(timeName);
});
},
/**
* get next date that matches parsed cron time
*/
_getNextDateFrom: function(start,zone) {
var date;
if(zone){
date=moment(start).tz(zone);
}
else{
date = moment(start);
}
if (!this.realDate) {
const milliseconds = (start.milliseconds && start.milliseconds()) || (start.getMilliseconds && start.getMilliseconds()) || 0;
if (milliseconds > 0) {
date.milliseconds(0);
date.seconds(date.seconds() + 1);
}
}
if (date.toString() == 'Invalid date') {
console.log('ERROR: You specified an invalid date.');
return date;
}
if (this.realDate && start < new Date()) {
console.log('WARNING: Date in past. Will never be fired.');
}
if (this.realDate) {
return date;
}
//sanity check
while (true) {
var diff = date - start,
origDate = new Date(date);
if (!(date.month() in this.month) && Object.keys(this.month).length!=12) {
date.add(1, 'M');
date.date(1);
date.hours(0);
date.minutes(0);
date.seconds(0);
continue;
}
if (!(date.date() in this.dayOfMonth) && Object.keys(this.dayOfMonth).length!=31) {
date.add(1, 'd');
date.hours(0);
date.minutes(0);
date.seconds(0);
continue;
}
if (!(date.day() in this.dayOfWeek) && Object.keys(this.dayOfWeek).length!=7) {
date.add(1, 'd');
date.hours(0);
date.minutes(0);
date.seconds(0);
if (date <= origDate) {
date = this._findDST(origDate);
}
continue;
}
if (!(date.hours() in this.hour) && Object.keys(this.hour).length!=24) {
origDate = moment(date);
date.hours(date.hours() == 23 && diff > 86400000 ? 0 : date.hours() + 1);
date.minutes(0);
date.seconds(0);
if (date <= origDate) {
date = this._findDST(origDate);
}
continue;
}
if (!(date.minutes() in this.minute) && Object.keys(this.minute).length!=60) {
origDate = moment(date);
date.minutes(date.minutes() == 59 && diff > 60 * 60 * 1000 ? 0 : date.minutes() + 1);
date.seconds(0);
if (date <= origDate) {
date = this._findDST(origDate);
}
continue;
}
if (!(date.seconds() in this.second) && Object.keys(this.second).length!=60) {
origDate = moment(date);
date.seconds(date.seconds() == 59 && diff > 60 * 1000 ? 0 : date.seconds() + 1);
if (date <= origDate) {
date = this._findDST(origDate);
}
continue;
}
if(date.valueOf()==start){
date.seconds(date.seconds()+1);
}
break;
}
if(origDate.valueOf()==start){
date.seconds(date.seconds()-1);
}
return date;
},
/**
* get next date that is a valid DST date
*/
_findDST: function(date) {
var newDate = moment(date);
while (newDate <= date)
newDate.add(1, 's');
return newDate;
},
/**
* wildcard, or all params in array (for to string)
*/
_wcOrAll: function(type) {
if (this._hasAll(type)) return '*';
var all = [];
for (var time in this[type]) {
all.push(time);
}
return all.join(',');
},
_hasAll: function(type) {
var constrain = CronTime.constraints[timeUnits.indexOf(type)];
for (var i = constrain[0], n = constrain[1]; i < n; i++) {
if (!(i in this[type]))
return false;
}
return true;
},
_parse: function() {
var aliases = CronTime.aliases;
var source = this.source.replace(/[a-z]{1,3}/ig, function(alias) {
alias = alias.toLowerCase();
if (alias in aliases) {
return aliases[alias];
}
throw new Error('Unknown alias: ' + alias);
});
var split = source.replace(/^\s\s*|\s\s*$/g, '').split(/\s+/);
var cur;
var i = 0;
var len = timeUnits.length;
for (; i < timeUnits.length; i++) {
// If the split source string doesn't contain all digits,
// assume defaults for first n missing digits.
// This adds support for 5-digit standard cron syntax
cur = split[i - (len - split.length)] || CronTime.parseDefaults[i];
this._parseField(cur, timeUnits[i], CronTime.constraints[i]);
}
},
_parseField: function(field, type, constraints) {
var rangePattern = /^(\d+)(?:-(\d+))?(?:\/(\d+))?$/g;
var typeObj = this[type];
var pointer;
var low = constraints[0];
var high = constraints[1];
// * is a shortcut to [lower-upper] range
field = field.replace(/\*/g, low + '-' + high);
//commas separate information, so split based on those
var allRanges = field.split(',');
for (var i = 0; i < allRanges.length; i++) {
if (allRanges[i].match(rangePattern)) {
allRanges[i].replace(rangePattern, function($0, lower, upper, step) {
step = parseInt(step) || 1;
// Positive integer higher than constraints[0]
lower = Math.min(Math.max(low, ~~Math.abs(lower)), high);
// Positive integer lower than constraints[1]
upper = upper ? Math.min(high, ~~Math.abs(upper)) : lower;
// Count from the lower barrier to the upper
pointer = lower;
do {
typeObj[pointer] = true
pointer += step;
} while (pointer <= upper);
});
} else {
throw new Error('Field (' + field + ') cannot be parsed');
}
}
}
};
function command2function(cmd) {
var command;
var args;
switch (typeof cmd) {
case 'string':
args = cmd.split(' ');
command = args.shift();
cmd = spawn.bind(undefined, command, args);
break;
case 'object':
command = cmd && cmd.command;
if (command) {
args = cmd.args;
var options = cmd.options;
cmd = spawn.bind(undefined, command, args, options);
}
break;
}
return cmd
}
function CronJob(cronTime, onTick, onComplete, startNow, timeZone, context, runOnInit, utcOffset) {
var _cronTime = cronTime;
var argCount = 0;
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] !== undefined) {
argCount++;
}
}
if (typeof cronTime != 'string' && argCount == 1) {
//crontime is an object...
onTick = cronTime.onTick;
onComplete = cronTime.onComplete;
context = cronTime.context;
startNow = cronTime.start || cronTime.startNow || cronTime.startJob;
timeZone = cronTime.timeZone;
runOnInit = cronTime.runOnInit;
_cronTime = cronTime.cronTime;
utcOffset = cronTime.utcOffset;
}
this.context = (context || this);
this._callbacks = [];
this.onComplete = command2function(onComplete);
this.cronTime = new CronTime(_cronTime, timeZone, utcOffset);
addCallback.call(this, command2function(onTick));
if (runOnInit) {
this.lastExecution = new Date();
fireOnTick.call(this);
}
if (startNow) {
start.call(this);
}
return this;
}
var addCallback = function(callback) {
if (typeof callback == 'function') this._callbacks.push(callback);
}
CronJob.prototype.addCallback = addCallback;
CronJob.prototype.setTime = function(time) {
if (!(time instanceof CronTime)) throw new Error('\'time\' must be an instance of CronTime.');
this.stop();
this.cronTime = time;
}
CronJob.prototype.nextDate = function() {
return this.cronTime.sendAt();
}
var fireOnTick = function() {
for (var i = (this._callbacks.length - 1); i >= 0; i--)
this._callbacks[i].call(this.context, this.onComplete);
}
CronJob.prototype.fireOnTick = fireOnTick;
CronJob.prototype.nextDates = function(i) {
return this.cronTime.sendAt(i);
}
var start = function() {
if (this.running) return;
var MAXDELAY = 2147483647; // The maximum number of milliseconds setTimeout will wait.
var self = this;
var timeout = this.cronTime.getTimeout();
var remaining = 0;
var startTime;
if (this.cronTime.realDate) this.runOnce = true;
function _setTimeout(timeout) {
startTime = Date.now();
self._timeout = setTimeout(callbackWrapper, timeout);
}
// The callback wrapper checks if it needs to sleep another period or not
// and does the real callback logic when it's time.
function callbackWrapper() {
var diff = startTime + timeout - Date.now();
if (diff > 0) {
var newTimeout = self.cronTime.getTimeout();
if (newTimeout > diff) {
newTimeout = diff;
}
remaining += newTimeout;
}
// If there is sleep time remaining, calculate how long and go to sleep
// again. This processing might make us miss the deadline by a few ms
// times the number of sleep sessions. Given a MAXDELAY of almost a
// month, this should be no issue.
self.lastExecution = new Date();
if (remaining) {
if (remaining > MAXDELAY) {
remaining -= MAXDELAY;
timeout = MAXDELAY;
} else {
timeout = remaining;
remaining = 0;
}
_setTimeout(timeout);
} else {
// We have arrived at the correct point in time.
self.running = false;
//start before calling back so the callbacks have the ability to stop the cron job
if (!(self.runOnce)) self.start();
self.fireOnTick();
//for (var i = (self._callbacks.length - 1); i >= 0; i--)
//self._callbacks[i].call(self.context, self.onComplete);
}
}
if (timeout >= 0) {
this.running = true;
// Don't try to sleep more than MAXDELAY ms at a time.
if (timeout > MAXDELAY) {
remaining = timeout - MAXDELAY;
timeout = MAXDELAY;
}
_setTimeout(timeout);
} else {
this.stop();
}
}
CronJob.prototype.start = start;
CronJob.prototype.lastDate = function(){
return this.lastExecution;
};
/**
* Stop the cronjob.
*/
CronJob.prototype.stop = function() {
if (this._timeout)
clearTimeout(this._timeout);
this.running = false;
if (typeof this.onComplete == 'function') this.onComplete();
}
exports.job = function(cronTime, onTick, onComplete, startNow, timeZone, context, runOnInit, utcOffset) {
return new CronJob(cronTime, onTick, onComplete, startNow, timeZone, context, runOnInit, utcOffset);
}
exports.time = function(cronTime, timeZone) {
return new CronTime(cronTime, timeZone);
}
exports.sendAt = function(cronTime) {
return exports.time(cronTime).sendAt();
}
exports.timeout = function(cronTime) {
return exports.time(cronTime).getTimeout();
}
exports.CronJob = CronJob;
exports.CronTime = CronTime;
return exports;
}));