cron 1.8.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/job.js ADDED
@@ -0,0 +1,214 @@
1
+ function CronJob(CronTime, spawn) {
2
+ function fnWrap(cmd) {
3
+ var command;
4
+ var args;
5
+
6
+ switch (typeof cmd) {
7
+ case 'string':
8
+ args = cmd.split(' ');
9
+ command = args.shift();
10
+
11
+ return spawn.bind(undefined, command, args);
12
+
13
+ case 'object':
14
+ command = cmd && cmd.command;
15
+ if (command) {
16
+ args = cmd.args;
17
+ var options = cmd.options;
18
+
19
+ return spawn.bind(undefined, command, args, options);
20
+ }
21
+ break;
22
+ }
23
+
24
+ return cmd;
25
+ }
26
+
27
+ function CJ(
28
+ cronTime,
29
+ onTick,
30
+ onComplete,
31
+ startNow,
32
+ timeZone,
33
+ context,
34
+ runOnInit,
35
+ utcOffset,
36
+ unrefTimeout
37
+ ) {
38
+ var _cronTime = cronTime;
39
+ var argCount = 0;
40
+ for (var i = 0; i < arguments.length; i++) {
41
+ if (arguments[i] !== undefined) {
42
+ argCount++;
43
+ }
44
+ }
45
+
46
+ if (typeof cronTime !== 'string' && argCount === 1) {
47
+ // crontime is an object...
48
+ onTick = cronTime.onTick;
49
+ onComplete = cronTime.onComplete;
50
+ context = cronTime.context;
51
+ startNow = cronTime.start || cronTime.startNow || cronTime.startJob;
52
+ timeZone = cronTime.timeZone;
53
+ runOnInit = cronTime.runOnInit;
54
+ _cronTime = cronTime.cronTime;
55
+ utcOffset = cronTime.utcOffset;
56
+ unrefTimeout = cronTime.unrefTimeout;
57
+ }
58
+
59
+ this.context = context || this;
60
+ this._callbacks = [];
61
+ this.onComplete = fnWrap(onComplete);
62
+ this.cronTime = new CronTime(_cronTime, timeZone, utcOffset);
63
+ this.unrefTimeout = unrefTimeout;
64
+
65
+ addCallback.call(this, fnWrap(onTick));
66
+
67
+ if (runOnInit) {
68
+ this.lastExecution = new Date();
69
+ fireOnTick.call(this);
70
+ }
71
+
72
+ if (startNow) {
73
+ start.call(this);
74
+ }
75
+
76
+ return this;
77
+ }
78
+
79
+ var addCallback = function (callback) {
80
+ if (typeof callback === 'function') {
81
+ this._callbacks.push(callback);
82
+ }
83
+ };
84
+ CJ.prototype.addCallback = addCallback;
85
+
86
+ CJ.prototype.setTime = function (time) {
87
+ if (typeof time !== 'object') {
88
+ // crontime is an object...
89
+ throw new Error('time must be an instance of CronTime.');
90
+ }
91
+ this.stop();
92
+ this.cronTime = time;
93
+ this.start();
94
+ };
95
+
96
+ CJ.prototype.nextDate = function () {
97
+ return this.cronTime.sendAt();
98
+ };
99
+
100
+ var fireOnTick = function () {
101
+ for (var i = this._callbacks.length - 1; i >= 0; i--) {
102
+ this._callbacks[i].call(this.context, this.onComplete);
103
+ }
104
+ };
105
+ CJ.prototype.fireOnTick = fireOnTick;
106
+
107
+ CJ.prototype.nextDates = function (i) {
108
+ return this.cronTime.sendAt(i);
109
+ };
110
+
111
+ var start = function () {
112
+ if (this.running) {
113
+ return;
114
+ }
115
+
116
+ var MAXDELAY = 2147483647; // The maximum number of milliseconds setTimeout will wait.
117
+ var self = this;
118
+ var timeout = this.cronTime.getTimeout();
119
+ var remaining = 0;
120
+ var startTime;
121
+
122
+ if (this.cronTime.realDate) {
123
+ this.runOnce = true;
124
+ }
125
+
126
+ function _setTimeout(timeout) {
127
+ startTime = Date.now();
128
+ self._timeout = setTimeout(callbackWrapper, timeout);
129
+ if (self.unrefTimeout && typeof self._timeout.unref === 'function') {
130
+ self._timeout.unref();
131
+ }
132
+ }
133
+
134
+ // The callback wrapper checks if it needs to sleep another period or not
135
+ // and does the real callback logic when it's time.
136
+ function callbackWrapper() {
137
+ var diff = startTime + timeout - Date.now();
138
+
139
+ if (diff > 0) {
140
+ var newTimeout = self.cronTime.getTimeout();
141
+
142
+ if (newTimeout > diff) {
143
+ newTimeout = diff;
144
+ }
145
+
146
+ remaining += newTimeout;
147
+ }
148
+
149
+ // If there is sleep time remaining, calculate how long and go to sleep
150
+ // again. This processing might make us miss the deadline by a few ms
151
+ // times the number of sleep sessions. Given a MAXDELAY of almost a
152
+ // month, this should be no issue.
153
+ self.lastExecution = new Date();
154
+ if (remaining) {
155
+ if (remaining > MAXDELAY) {
156
+ remaining -= MAXDELAY;
157
+ timeout = MAXDELAY;
158
+ } else {
159
+ timeout = remaining;
160
+ remaining = 0;
161
+ }
162
+
163
+ _setTimeout(timeout);
164
+ } else {
165
+ // We have arrived at the correct point in time.
166
+
167
+ self.running = false;
168
+
169
+ // start before calling back so the callbacks have the ability to stop the cron job
170
+ if (!self.runOnce) {
171
+ self.start();
172
+ }
173
+
174
+ self.fireOnTick();
175
+ }
176
+ }
177
+
178
+ if (timeout >= 0) {
179
+ this.running = true;
180
+
181
+ // Don't try to sleep more than MAXDELAY ms at a time.
182
+
183
+ if (timeout > MAXDELAY) {
184
+ remaining = timeout - MAXDELAY;
185
+ timeout = MAXDELAY;
186
+ }
187
+
188
+ _setTimeout(timeout);
189
+ } else {
190
+ this.stop();
191
+ }
192
+ };
193
+
194
+ CJ.prototype.start = start;
195
+
196
+ CJ.prototype.lastDate = function () {
197
+ return this.lastExecution;
198
+ };
199
+
200
+ /**
201
+ * Stop the cronjob.
202
+ */
203
+ CJ.prototype.stop = function () {
204
+ if (this._timeout) clearTimeout(this._timeout);
205
+ this.running = false;
206
+ if (typeof this.onComplete === 'function') {
207
+ this.onComplete();
208
+ }
209
+ };
210
+
211
+ return CJ;
212
+ }
213
+
214
+ module.exports = CronJob;
package/lib/time.js ADDED
@@ -0,0 +1,513 @@
1
+ const CONSTRAINTS = [
2
+ [0, 59],
3
+ [0, 59],
4
+ [0, 23],
5
+ [1, 31],
6
+ [0, 11],
7
+ [0, 6]
8
+ ];
9
+ const MONTH_CONSTRAINTS = [
10
+ 31,
11
+ 29, // support leap year...not perfect
12
+ 31,
13
+ 30,
14
+ 31,
15
+ 30,
16
+ 31,
17
+ 31,
18
+ 30,
19
+ 31,
20
+ 30,
21
+ 31
22
+ ];
23
+ const PARSE_DEFAULTS = ['0', '*', '*', '*', '*', '*'];
24
+ const ALIASES = {
25
+ jan: 0,
26
+ feb: 1,
27
+ mar: 2,
28
+ apr: 3,
29
+ may: 4,
30
+ jun: 5,
31
+ jul: 6,
32
+ aug: 7,
33
+ sep: 8,
34
+ oct: 9,
35
+ nov: 10,
36
+ dec: 11,
37
+ sun: 0,
38
+ mon: 1,
39
+ tue: 2,
40
+ wed: 3,
41
+ thu: 4,
42
+ fri: 5,
43
+ sat: 6
44
+ };
45
+ const TIME_UNITS = [
46
+ 'second',
47
+ 'minute',
48
+ 'hour',
49
+ 'dayOfMonth',
50
+ 'month',
51
+ 'dayOfWeek'
52
+ ];
53
+ const TIME_UNITS_LEN = TIME_UNITS.length;
54
+ const PRESETS = {
55
+ '@yearly': '0 0 0 1 0 *',
56
+ '@monthly': '0 0 0 1 * *',
57
+ '@weekly': '0 0 0 * * 0',
58
+ '@daily': '0 0 0 * * *',
59
+ '@hourly': '0 0 * * * *',
60
+ '@minutely': '0 * * * * *',
61
+ '@secondly': '* * * * * *',
62
+ '@weekdays': '0 0 0 * * 1-5',
63
+ '@weekends': '0 0 0 * * 0,6'
64
+ };
65
+ const RE_WILDCARDS = /\*/g;
66
+ const RE_RANGE = /^(\d+)(?:-(\d+))?(?:\/(\d+))?$/g;
67
+
68
+ function CronTime(luxon) {
69
+ function CT(source, zone, utcOffset) {
70
+ this.source = source;
71
+
72
+ if (zone) {
73
+ const dt = luxon.DateTime.fromObject({ zone: zone });
74
+ if (dt.invalid) {
75
+ throw new Error('Invalid timezone.');
76
+ }
77
+
78
+ this.zone = zone;
79
+ }
80
+
81
+ if (typeof utcOffset !== 'undefined') {
82
+ this.utcOffset = utcOffset;
83
+ }
84
+
85
+ var that = this;
86
+ TIME_UNITS.map(timeUnit => {
87
+ that[timeUnit] = {};
88
+ });
89
+
90
+ if (this.source instanceof Date || this.source instanceof luxon.DateTime) {
91
+ if (this.source instanceof Date) {
92
+ this.source = luxon.DateTime.fromJSDate(this.source);
93
+ }
94
+ this.realDate = true;
95
+ } else {
96
+ this._parse(this.source);
97
+ this._verifyParse();
98
+ }
99
+ }
100
+
101
+ CT.prototype = {
102
+ /*
103
+ * Ensure that the syntax parsed correctly and correct the specified values if needed.
104
+ */
105
+ _verifyParse: function () {
106
+ var months = Object.keys(this.month);
107
+ var dom = Object.keys(this.dayOfMonth);
108
+ var ok = false;
109
+
110
+ /* if a dayOfMonth is not found in all months, we only need to fix the last
111
+ wrong month to prevent infinite loop */
112
+ var lastWrongMonth = NaN;
113
+ for (var i = 0; i < months.length; i++) {
114
+ var m = months[i];
115
+ var con = MONTH_CONSTRAINTS[parseInt(m, 10)];
116
+
117
+ for (var j = 0; j < dom.length; j++) {
118
+ var day = dom[j];
119
+ if (day <= con) {
120
+ ok = true;
121
+ }
122
+ }
123
+
124
+ if (!ok) {
125
+ // save the month in order to be fixed if all months fails (infinite loop)
126
+ lastWrongMonth = m;
127
+ console.warn(`Month '${m}' is limited to '${con}' days.`);
128
+ }
129
+ }
130
+
131
+ // infinite loop detected (dayOfMonth is not found in all months)
132
+ if (!ok) {
133
+ var notOkCon = MONTH_CONSTRAINTS[parseInt(lastWrongMonth, 10)];
134
+ for (var k = 0; k < dom.length; k++) {
135
+ var notOkDay = dom[k];
136
+ if (notOkDay > notOkCon) {
137
+ delete this.dayOfMonth[notOkDay];
138
+ var fixedDay = Number(notOkDay) % notOkCon;
139
+ this.dayOfMonth[fixedDay] = true;
140
+ }
141
+ }
142
+ }
143
+ },
144
+
145
+ /**
146
+ * Calculate the "next" scheduled time
147
+ */
148
+ sendAt: function (i) {
149
+ var date = this.realDate ? this.source : luxon.DateTime.local();
150
+ if (this.zone) {
151
+ date = date.setZone(this.zone);
152
+ }
153
+
154
+ if (typeof this.utcOffset !== 'undefined') {
155
+ let offset =
156
+ this.utcOffset >= 60 || this.utcOffset <= -60
157
+ ? this.utcOffset / 60
158
+ : this.utcOffset;
159
+ offset = parseInt(offset);
160
+
161
+ let utcZone = 'UTC';
162
+ if (offset < 0) {
163
+ utcZone += offset;
164
+ } else if (offset > 0) {
165
+ utcZone += `+${offset}`;
166
+ }
167
+
168
+ date = date.setZone(utcZone);
169
+
170
+ if (date.invalid) {
171
+ throw new Error('ERROR: You specified an invalid UTC offset.');
172
+ }
173
+ }
174
+
175
+ if (this.realDate) {
176
+ if (luxon.DateTime.local() > date) {
177
+ throw new Error('WARNING: Date in past. Will never be fired.');
178
+ }
179
+
180
+ return date;
181
+ }
182
+
183
+ if (isNaN(i) || i < 0) {
184
+ // just get the next scheduled time
185
+ return this._getNextDateFrom(date);
186
+ } else {
187
+ // return the next schedule times
188
+ var dates = [];
189
+ for (; i > 0; i--) {
190
+ date = this._getNextDateFrom(date);
191
+ dates.push(date);
192
+ }
193
+
194
+ return dates;
195
+ }
196
+ },
197
+
198
+ /**
199
+ * Get the number of milliseconds in the future at which to fire our callbacks.
200
+ */
201
+ getTimeout: function () {
202
+ return Math.max(-1, this.sendAt() - luxon.DateTime.local());
203
+ },
204
+
205
+ /**
206
+ * writes out a cron string
207
+ */
208
+ toString: function () {
209
+ return this.toJSON().join(' ');
210
+ },
211
+
212
+ /**
213
+ * Json representation of the parsed cron syntax.
214
+ */
215
+ toJSON: function () {
216
+ var self = this;
217
+ return TIME_UNITS.map(function (timeName) {
218
+ return self._wcOrAll(timeName);
219
+ });
220
+ },
221
+
222
+ /**
223
+ * Get next date matching the specified cron time.
224
+ *
225
+ * Algorithm:
226
+ * - Start with a start date and a parsed crontime.
227
+ * - Loop until 5 seconds have passed, or we found the next date.
228
+ * - Within the loop:
229
+ * - If it took longer than 5 seconds to select a date, throw an exception.
230
+ * - Find the next month to run at.
231
+ * - Find the next day of the month to run at.
232
+ * - Find the next day of the week to run at.
233
+ * - Find the next hour to run at.
234
+ * - Find the next minute to run at.
235
+ * - Find the next second to run at.
236
+ * - Check that the chosen time does not equal the current execution.
237
+ * - Return the selected date object.
238
+ */
239
+ _getNextDateFrom: function (start, zone) {
240
+ if (start instanceof Date) {
241
+ start = luxon.DateTime.fromJSDate(start);
242
+ }
243
+ var date = start;
244
+ var firstDate = start.toMillis();
245
+ if (zone) {
246
+ date = date.setZone(zone);
247
+ }
248
+ if (!this.realDate) {
249
+ if (date.millisecond > 0) {
250
+ date = date.set({ millisecond: 0, second: date.second + 1 });
251
+ }
252
+ }
253
+
254
+ if (date.invalid) {
255
+ throw new Error('ERROR: You specified an invalid date.');
256
+ }
257
+
258
+ // it shouldn't take more than 5 seconds to find the next execution time
259
+ // being very generous with this. Throw error if it takes too long to find the next time to protect from
260
+ // infinite loop.
261
+ var timeout = Date.now() + 5000;
262
+ // determine next date
263
+ while (true) {
264
+ var diff = date - start;
265
+
266
+ // hard stop if the current date is after the expected execution
267
+ if (Date.now() > timeout) {
268
+ throw new Error(
269
+ `Something went wrong. It took over five seconds to find the next execution time for the cron job.
270
+ Please refer to the canonical issue (https://github.com/kelektiv/node-cron/issues/467) and provide the following string if you would like to help debug:
271
+ Time Zone: ${zone || '""'} - Cron String: ${this} - UTC offset: ${date.format(
272
+ 'Z'
273
+ )} - current Date: ${luxon.DateTime.local().toString()}`
274
+ );
275
+ }
276
+
277
+ if (
278
+ !(date.month - 1 in this.month) &&
279
+ Object.keys(this.month).length !== 12
280
+ ) {
281
+ date = date.plus({ months: 1 });
282
+ date = date.set({ day: 1, hour: 0, minute: 0, second: 0 });
283
+ continue;
284
+ }
285
+
286
+ if (
287
+ !(date.day in this.dayOfMonth) &&
288
+ Object.keys(this.dayOfMonth).length !== 31 &&
289
+ !(
290
+ date.getWeekDay() in this.dayOfWeek &&
291
+ Object.keys(this.dayOfWeek).length !== 7
292
+ )
293
+ ) {
294
+ date = date.plus({ days: 1 });
295
+ date = date.set({ hour: 0, minute: 0, second: 0 });
296
+ continue;
297
+ }
298
+
299
+ if (
300
+ !(date.getWeekDay() in this.dayOfWeek) &&
301
+ Object.keys(this.dayOfWeek).length !== 7 &&
302
+ !(
303
+ date.day in this.dayOfMonth &&
304
+ Object.keys(this.dayOfMonth).length !== 31
305
+ )
306
+ ) {
307
+ date = date.plus({ days: 1 });
308
+ date = date.set({ hour: 0, minute: 0, second: 0 });
309
+ continue;
310
+ }
311
+
312
+ if (!(date.hour in this.hour) && Object.keys(this.hour).length !== 24) {
313
+ date = date.set({
314
+ hour: date.hour === 23 && diff > 86400000 ? 0 : date.hour + 1
315
+ });
316
+ date = date.set({ minute: 0, second: 0 });
317
+ continue;
318
+ }
319
+
320
+ if (
321
+ !(date.minute in this.minute) &&
322
+ Object.keys(this.minute).length !== 60
323
+ ) {
324
+ date = date.set({
325
+ minute: date.minute === 59 && diff > 3600000 ? 0 : date.minute + 1
326
+ });
327
+ date = date.set({ second: 0 });
328
+ continue;
329
+ }
330
+
331
+ if (
332
+ !(date.second in this.second) &&
333
+ Object.keys(this.second).length !== 60
334
+ ) {
335
+ date = date.set({
336
+ second: date.second === 59 && diff > 60000 ? 0 : date.second + 1
337
+ });
338
+ continue;
339
+ }
340
+
341
+ if (date.toMillis() === firstDate) {
342
+ date = date.set({ second: date.second + 1 });
343
+ continue;
344
+ }
345
+
346
+ break;
347
+ }
348
+
349
+ return date;
350
+ },
351
+
352
+ /**
353
+ * wildcard, or all params in array (for to string)
354
+ */
355
+ _wcOrAll: function (type) {
356
+ if (this._hasAll(type)) {
357
+ return '*';
358
+ }
359
+
360
+ var all = [];
361
+ for (var time in this[type]) {
362
+ all.push(time);
363
+ }
364
+
365
+ return all.join(',');
366
+ },
367
+
368
+ _hasAll: function (type) {
369
+ var constraints = CONSTRAINTS[TIME_UNITS.indexOf(type)];
370
+
371
+ for (var i = constraints[0], n = constraints[1]; i < n; i++) {
372
+ if (!(i in this[type])) {
373
+ return false;
374
+ }
375
+ }
376
+
377
+ return true;
378
+ },
379
+
380
+ /*
381
+ * Parse the cron syntax into something useful for selecting the next execution time.
382
+ *
383
+ * Algorithm:
384
+ * - Replace preset
385
+ * - Replace aliases in the source.
386
+ * - Trim string and split for processing.
387
+ * - Loop over split options (ms -> month):
388
+ * - Get the value (or default) in the current position.
389
+ * - Parse the value.
390
+ */
391
+ _parse: function (source) {
392
+ source = source.toLowerCase();
393
+
394
+ if (source in PRESETS) {
395
+ source = PRESETS[source];
396
+ }
397
+
398
+ source = source.replace(/[a-z]{1,3}/gi, alias => {
399
+ if (alias in ALIASES) {
400
+ return ALIASES[alias];
401
+ }
402
+
403
+ throw new Error(`Unknown alias: ${alias}`);
404
+ });
405
+
406
+ var units = source.trim().split(/\s+/);
407
+
408
+ // seconds are optional
409
+ if (units.length < TIME_UNITS_LEN - 1) {
410
+ throw new Error('Too few fields');
411
+ }
412
+
413
+ if (units.length > TIME_UNITS_LEN) {
414
+ throw new Error('Too many fields');
415
+ }
416
+
417
+ var unitsLen = units.length;
418
+ for (var i = 0; i < TIME_UNITS_LEN; i++) {
419
+ // If the split source string doesn't contain all digits,
420
+ // assume defaults for first n missing digits.
421
+ // This adds support for 5-digit standard cron syntax
422
+ var cur = units[i - (TIME_UNITS_LEN - unitsLen)] || PARSE_DEFAULTS[i];
423
+ this._parseField(cur, TIME_UNITS[i], CONSTRAINTS[i]);
424
+ }
425
+ },
426
+
427
+ /*
428
+ * Parse individual field from the cron syntax provided.
429
+ *
430
+ * Algorithm:
431
+ * - Split field by commas aand check for wildcards to ensure proper user.
432
+ * - Replace wildcard values with <low>-<high> boundaries.
433
+ * - Split field by commas and then iterate over ranges inside field.
434
+ * - If range matches pattern then map over matches using replace (to parse the range by the regex pattern)
435
+ * - Starting with the lower bounds of the range iterate by step up to the upper bounds and toggle the CronTime field value flag on.
436
+ */
437
+ _parseField: function (value, type, constraints) {
438
+ var typeObj = this[type];
439
+ var pointer;
440
+ var low = constraints[0];
441
+ var high = constraints[1];
442
+
443
+ var fields = value.split(',');
444
+ fields.forEach(field => {
445
+ var wildcardIndex = field.indexOf('*');
446
+ if (wildcardIndex !== -1 && wildcardIndex !== 0) {
447
+ throw new Error(
448
+ `Field (${field}) has an invalid wildcard expression`
449
+ );
450
+ }
451
+ });
452
+
453
+ // * is a shortcut to [low-high] range for the field
454
+ value = value.replace(RE_WILDCARDS, `${low}-${high}`);
455
+
456
+ // commas separate information, so split based on those
457
+ var allRanges = value.split(',');
458
+
459
+ for (var i = 0; i < allRanges.length; i++) {
460
+ if (allRanges[i].match(RE_RANGE)) {
461
+ allRanges[i].replace(RE_RANGE, ($0, lower, upper, step) => {
462
+ lower = parseInt(lower, 10);
463
+ upper = parseInt(upper, 10) || undefined;
464
+
465
+ const wasStepDefined = !isNaN(parseInt(step, 10));
466
+ if (step === '0') {
467
+ throw new Error(`Field (${type}) has a step of zero`);
468
+ }
469
+ step = parseInt(step, 10) || 1;
470
+
471
+ if (upper && lower > upper) {
472
+ throw new Error(`Field (${type}) has an invalid range`);
473
+ }
474
+
475
+ const outOfRangeError =
476
+ lower < low ||
477
+ (upper && upper > high) ||
478
+ (!upper && lower > high);
479
+
480
+ if (outOfRangeError) {
481
+ throw new Error(`Field value (${value}) is out of range`);
482
+ }
483
+
484
+ // Positive integer higher than constraints[0]
485
+ lower = Math.min(Math.max(low, ~~Math.abs(lower)), high);
486
+
487
+ // Positive integer lower than constraints[1]
488
+ if (upper) {
489
+ upper = Math.min(high, ~~Math.abs(upper));
490
+ } else {
491
+ // If step is provided, the default upper range is the highest value
492
+ upper = wasStepDefined ? high : lower;
493
+ }
494
+
495
+ // Count from the lower barrier to the upper
496
+ pointer = lower;
497
+
498
+ do {
499
+ typeObj[pointer] = true; // mutates the field objects values inside CronTime
500
+ pointer += step;
501
+ } while (pointer <= upper);
502
+ });
503
+ } else {
504
+ throw new Error(`Field (${type}) cannot be parsed`);
505
+ }
506
+ }
507
+ }
508
+ };
509
+
510
+ return CT;
511
+ }
512
+
513
+ module.exports = CronTime;