cron 1.0.5 → 1.0.9

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/cron.js CHANGED
@@ -1,451 +1,478 @@
1
- var CronDate;
2
- var exports;
3
- var timeUnits = ['second', 'minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
4
- var loadedTimeModule = false;
5
-
6
- try {
7
- CronDate = require("time").Date;
8
- exports = module.exports;
9
- loadedTimeModule = true;
10
- } catch (e) {
11
- CronDate = Date;
12
- }
1
+ var exports,
2
+ timeUnits = ['second', 'minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'],
3
+ spawn = require('child_process').spawn,
4
+ moment = require('moment-timezone');
13
5
 
14
6
  function CronTime(source, zone) {
15
- this.source = source;
16
- this.zone = zone;
17
-
18
- var that = this;
19
- timeUnits.map(function(timeUnit){
20
- that[timeUnit] = {};
21
- });
22
-
23
- if ((this.source instanceof Date) || (this.source instanceof CronDate)) {
24
- this.source = new CronDate(this.source);
25
- this.realDate = true;
26
- } else {
27
- this._parse();
28
- }
7
+ this.source = source;
8
+ this.zone = zone;
9
+
10
+ var that = this;
11
+ timeUnits.map(function(timeUnit){
12
+ that[timeUnit] = {};
13
+ });
14
+
15
+ if (this.source instanceof Date) {
16
+ this.source = moment(this.source);
17
+ this.realDate = true;
18
+ } else {
19
+ this._parse();
20
+ if (!this._verifyParse())
21
+ throw Error("Could not verify a valid date. Please verify your parameters.");
22
+ }
29
23
  }
30
24
 
31
25
  CronTime.constraints = [
32
- [0, 59],
33
- [0, 59],
34
- [0, 23],
35
- [1, 31],
36
- [0, 11],
37
- [0, 6]
38
- ];
39
- CronTime.parseDefaults = ['0', '*', '*', '*', '*', '*'];
40
- CronTime.aliases = {
41
- jan: 0,
42
- feb: 1,
43
- mar: 2,
44
- apr: 3,
45
- may: 4,
46
- jun: 5,
47
- jul: 6,
48
- aug: 7,
49
- sep: 8,
50
- oct: 9,
51
- nov: 10,
52
- dec: 11,
53
- sun: 0,
54
- mon: 1,
55
- tue: 2,
56
- wed: 3,
57
- thu: 4,
58
- fri: 5,
59
- sat: 6
60
- };
26
+ [0, 59],
27
+ [0, 59],
28
+ [0, 23],
29
+ [1, 31],
30
+ [0, 11],
31
+ [0, 6]
32
+ ];
33
+ CronTime.monthConstraints = [
34
+ 31,
35
+ 29, //support leap year...not perfect
36
+ 31,
37
+ 30,
38
+ 31,
39
+ 30,
40
+ 31,
41
+ 31,
42
+ 30,
43
+ 31,
44
+ 30,
45
+ 31
46
+ ];
47
+ CronTime.parseDefaults = ['0', '*', '*', '*', '*', '*'];
48
+ CronTime.aliases = {
49
+ jan: 0,
50
+ feb: 1,
51
+ mar: 2,
52
+ apr: 3,
53
+ may: 4,
54
+ jun: 5,
55
+ jul: 6,
56
+ aug: 7,
57
+ sep: 8,
58
+ oct: 9,
59
+ nov: 10,
60
+ dec: 11,
61
+ sun: 0,
62
+ mon: 1,
63
+ tue: 2,
64
+ wed: 3,
65
+ thu: 4,
66
+ fri: 5,
67
+ sat: 6
68
+ };
61
69
 
62
70
 
63
71
  CronTime.prototype = {
64
- /**
65
- * calculates the next send time
66
- */
67
- sendAt: function() {
68
- var date = (this.source instanceof CronDate) ? this.source : new CronDate();
69
- if (this.zone && date.setTimezone)
70
- date.setTimezone(this.zone);
71
-
72
- //add 1 second so next time isn't now (can cause timeout to be 0)
73
- if (!(this.realDate)) date.setSeconds(date.getSeconds() + 1);
74
-
75
- if (this.realDate) {
76
- return date;
77
- }
78
- return this._getNextDateFrom(date);
79
- },
80
-
81
- /**
82
- * Get the number of milliseconds in the future at which to fire our callbacks.
83
- */
84
- getTimeout: function() {
85
- return Math.max(-1, this.sendAt().getTime() - CronDate.now());
86
- },
87
-
88
- /**
89
- * writes out a cron string
90
- */
91
- toString: function() {
92
- return this.toJSON().join(' ');
93
- },
94
-
95
- /**
96
- * Json representation of the parsed cron syntax.
97
- */
98
- toJSON: function() {
99
- var that = this;
100
- return timeUnits.map(function(timeName){
101
- return that._wcOrAll(timeName);
102
- });
103
- },
104
-
105
- /**
106
- * get next date that matches parsed cron time
107
- */
108
- _getNextDateFrom: function(start) {
109
- var date = new CronDate(start);
110
- //console.log("d: " + date);
111
- if (this.zone && date.setTimezone)
112
- date.setTimezone(this.zone);
113
- if (this.realDate && start < new Date())
114
- console.log("WARNING: Date in past. Will never be fired.");
115
- if (this.realDate) return date;
116
-
117
- //sanity check
118
- //var i = 1000;
119
- while (1) {
120
- var diff = date - start,
121
- origDate = new Date(date);
122
-
123
- if (!(date.getMonth() in this.month)) {
124
- date.setMonth(date.getMonth() + 1);
125
- date.setDate(1);
126
- date.setHours(0);
127
- date.setMinutes(0);
128
- continue;
129
- }
130
-
131
- if (!(date.getDate() in this.dayOfMonth)) {
132
- date.setDate(date.getDate() + 1);
133
- date.setHours(0);
134
- date.setMinutes(0);
135
- continue;
136
- }
137
-
138
- if (!(date.getDay() in this.dayOfWeek)) {
139
- date.setDate(date.getDate() + 1);
140
- date.setHours(0);
141
- date.setMinutes(0);
142
- date.setSeconds(0);
143
- if (date <= origDate) {
144
- date = this._findDST(origDate);
145
- }
146
- continue;
147
- }
148
-
149
- if (!(date.getHours() in this.hour)) {
150
- origDate = new Date(date);
151
- date.setHours(date.getHours() == 23 && diff > 24 * 60 * 60 * 1000 ? 0 : date.getHours() + 1);
152
- date.setMinutes(0);
153
- date.setSeconds(0);
154
- if (date <= origDate) {
155
- date = this._findDST(origDate);
156
- }
157
- continue;
158
- }
159
-
160
- if (!(date.getMinutes() in this.minute)) {
161
- origDate = new Date(date);
162
- date.setMinutes(date.getMinutes() == 59 && diff > 60 * 60 * 1000 ? 0 : date.getMinutes() + 1);
163
- date.setSeconds(0);
164
- if (date <= origDate) {
165
- date = this._findDST(origDate);
166
- }
167
- continue;
168
- }
169
-
170
- if (!(date.getSeconds() in this.second)) {
171
- origDate = new Date(date);
172
- date.setSeconds(date.getSeconds() == 59 && diff > 60 * 1000 ? 0 : date.getSeconds() + 1);
173
- if (date <= origDate) {
174
- date = this._findDST(origDate);
175
- }
176
- continue;
177
- }
178
-
179
- break;
180
- }
181
-
182
- return date;
183
- },
184
-
185
- /**
186
- * get next date that is a valid DST date
187
- */
188
- _findDST: function(date) {
189
- var newDate = new Date(date),
190
- addSeconds = 1;
191
- while (newDate <= date) {
192
- newDate.setSeconds(date.getSeconds() + addSeconds++);
193
- }
194
-
195
- return newDate;
196
- },
197
-
198
- /**
199
- * wildcard, or all params in array (for to string)
200
- */
201
- _wcOrAll: function(type) {
202
- if (this._hasAll(type)) return '*';
203
-
204
- var all = [];
205
- for (var time in this[type]) {
206
- all.push(time);
207
- }
208
-
209
- return all.join(',');
210
- },
211
-
212
- /**
213
- */
214
- _hasAll: function(type) {
215
- var constrain = CronTime.constraints[timeUnits.indexOf(type)];
216
-
217
- for (var i = constrain[0], n = constrain[1]; i < n; i++) {
218
- if (!(i in this[type])) return false;
219
- }
220
-
221
- return true;
222
- },
223
-
224
-
225
- /**
226
- * Parse the cron syntax.
227
- */
228
- _parse: function() {
229
- var aliases = CronTime.aliases,
230
- source = this.source.replace(/[a-z]{1,3}/ig, function(alias) {
231
- alias = alias.toLowerCase();
232
-
233
- if (alias in aliases) {
234
- return aliases[alias];
235
- }
236
-
237
- throw new Error('Unknown alias: ' + alias);
238
- }),
239
- split = source.replace(/^\s\s*|\s\s*$/g, '').split(/\s+/),
240
- cur, i = 0,
241
- len = timeUnits.length;
242
-
243
- for (; i < timeUnits.length; i++) {
244
- // If the split source string doesn't contain all digits,
245
- // assume defaults for first n missing digits.
246
- // This adds support for 5-digit standard cron syntax
247
- cur = split[i - (len - split.length)] || CronTime.parseDefaults[i];
248
- this._parseField(cur, timeUnits[i], CronTime.constraints[i]);
249
- }
250
- },
251
-
252
- /**
253
- * Parse a field from the cron syntax.
254
- */
255
- _parseField: function(field, type, constraints) {
256
-
257
- //var rangePattern = /^(\*)(?:\/(\d+))?$|(\d+)(?:-(\d+))?(?:\/(\d+))?(?:,|$)/g
258
- var rangePattern = /^(\d+)(?:-(\d+))?(?:\/(\d+))?$/g,
259
- typeObj = this[type],
260
- diff, pointer,
261
- low = constraints[0],
262
- high = constraints[1];
263
-
264
- // * is a shortcut to [lower-upper] range
265
- field = field.replace(/\*/g, low + '-' + high);
266
-
267
- //commas separate information, so split based on those
268
- var allRanges = field.split(',');
269
-
270
- for (var i = 0; i < allRanges.length; i++) {
271
- if (allRanges[i].match(rangePattern)) {
272
- allRanges[i].replace(rangePattern, function($0, lower, upper, step) {
273
- step = parseInt(step) || 1;
274
- // Positive integer higher than constraints[0]
275
- lower = Math.min(Math.max(low, ~~Math.abs(lower)), high);
276
-
277
- // Positive integer lower than constraints[1]
278
- upper = upper ? Math.min(high, ~~Math.abs(upper)) : lower;
279
-
280
- // Count from the lower barrier to the upper
281
- pointer = lower;
282
-
283
- do {
284
- typeObj[pointer] = true
285
- pointer += step;
286
- } while (pointer <= upper);
287
-
288
- });
289
- } else {
290
- throw new Error('Field (' + field + ') cannot be parsed');
291
- }
292
- }
293
- }
72
+ _verifyParse: function() {
73
+ var months = Object.keys(this.month);
74
+ for (var i = 0; i < months.length; i++) {
75
+ var m = months[i];
76
+ var con = CronTime.monthConstraints[parseInt(m, 10)];
77
+ var ok = false;
78
+ var dsom = Object.keys(this.dayOfMonth);
79
+ for (var j = 0; j < dsom.length; j++) {
80
+ var dom = dsom[j];
81
+ if (dom <= con)
82
+ ok = true;
83
+ }
84
+
85
+ if (!ok) {
86
+ console.error("Month '" + m + "' is limited to '" + con + "' days.");
87
+ return false;
88
+ }
89
+ }
90
+
91
+ return true;
92
+ },
93
+
94
+ /**
95
+ * calculates the next send time
96
+ */
97
+ sendAt: function() {
98
+ var date = this.realDate ? this.source : moment();
99
+ // Set the timezone if given (http://momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone/)
100
+ if (this.zone)
101
+ date = date.tz(this.zone);
102
+
103
+ if (this.realDate)
104
+ return date;
105
+
106
+ //add 1 second so next time isn't now (can cause timeout to be 0 or negative number)
107
+ var now = new Date();
108
+ var targetSecond = date.seconds();
109
+ var diff = Math.abs(targetSecond - now.getSeconds())
110
+ // there was a problem when `date` is 1424777177999 and `now` is 1424777178000
111
+ // 1 ms diff but this is another second...
112
+ if ( diff == 0 || (diff == 1 && now.getMilliseconds() <= date.milliseconds() ) ) {
113
+ //console.log('add 1 second?');
114
+ date = date.add(1, 's');
115
+ }
116
+
117
+ date = this._getNextDateFrom(date);
118
+
119
+ return date;
120
+ },
121
+
122
+ /**
123
+ * Get the number of milliseconds in the future at which to fire our callbacks.
124
+ */
125
+ getTimeout: function() {
126
+ return Math.max(-1, this.sendAt() - moment());
127
+ },
128
+
129
+ /**
130
+ * writes out a cron string
131
+ */
132
+ toString: function() {
133
+ return this.toJSON().join(' ');
134
+ },
135
+
136
+ /**
137
+ * Json representation of the parsed cron syntax.
138
+ */
139
+ toJSON: function() {
140
+ var self = this;
141
+ return timeUnits.map(function(timeName){
142
+ return self._wcOrAll(timeName);
143
+ });
144
+ },
145
+
146
+ /**
147
+ * get next date that matches parsed cron time
148
+ */
149
+ _getNextDateFrom: function(start) {
150
+ var date = moment(start);
151
+ if (date.toString() == 'Invalid date') {
152
+ console.log("ERROR: You specified an invalid date.");
153
+ return date;
154
+ }
155
+ if (this.realDate && start < new Date())
156
+ console.log("WARNING: Date in past. Will never be fired.");
157
+ if (this.realDate) return date;
158
+
159
+ //sanity check
160
+ while (1) {
161
+ var diff = date - start,
162
+ origDate = new Date(date);
163
+
164
+ if (!(date.month() in this.month)) {
165
+ date.add(1, 'M');
166
+ date.date(1);
167
+ date.hours(0);
168
+ date.minutes(0);
169
+ date.seconds(0);
170
+ continue;
171
+ }
172
+
173
+ if (!(date.date() in this.dayOfMonth)) {
174
+ date.add(1, 'd');
175
+ date.hours(0);
176
+ date.minutes(0);
177
+ date.seconds(0);
178
+ continue;
179
+ }
180
+
181
+ if (!(date.day() in this.dayOfWeek)) {
182
+ date.add(1, 'd');
183
+ date.hours(0);
184
+ date.minutes(0);
185
+ date.seconds(0);
186
+ if (date <= origDate) {
187
+ date = this._findDST(origDate);
188
+ }
189
+ continue;
190
+ }
191
+
192
+ if (!(date.hours() in this.hour)) {
193
+ origDate = moment(date);
194
+ date.hours(date.hours() == 23 && diff > 86400000 ? 0 : date.hours() + 1);
195
+ date.minutes(0);
196
+ date.seconds(0);
197
+ if (date <= origDate) {
198
+ date = this._findDST(origDate);
199
+ }
200
+ continue;
201
+ }
202
+
203
+ if (!(date.minutes() in this.minute)) {
204
+ origDate = moment(date);
205
+ date.minutes(date.minutes() == 59 && diff > 60 * 60 * 1000 ? 0 : date.minutes() + 1);
206
+ date.seconds(0);
207
+ if (date <= origDate) {
208
+ date = this._findDST(origDate);
209
+ }
210
+ continue;
211
+ }
212
+
213
+ if (!(date.seconds() in this.second)) {
214
+ origDate = moment(date);
215
+ date.seconds(date.seconds() == 59 && diff > 60 * 1000 ? 0 : date.seconds() + 1);
216
+ if (date <= origDate) {
217
+ date = this._findDST(origDate);
218
+ }
219
+ continue;
220
+ }
221
+
222
+ break;
223
+ }
224
+
225
+ return date;
226
+ },
227
+
228
+ /**
229
+ * get next date that is a valid DST date
230
+ */
231
+ _findDST: function(date) {
232
+ var newDate = moment(date),
233
+ addSeconds = 1;
234
+ while (newDate <= date)
235
+ newDate.add(1, 's');
236
+
237
+ return newDate;
238
+ },
239
+
240
+ /**
241
+ * wildcard, or all params in array (for to string)
242
+ */
243
+ _wcOrAll: function(type) {
244
+ if (this._hasAll(type)) return '*';
245
+
246
+ var all = [];
247
+ for (var time in this[type]) {
248
+ all.push(time);
249
+ }
250
+
251
+ return all.join(',');
252
+ },
253
+
254
+ _hasAll: function(type) {
255
+ var constrain = CronTime.constraints[timeUnits.indexOf(type)];
256
+
257
+ for (var i = constrain[0], n = constrain[1]; i < n; i++) {
258
+ if (!(i in this[type])) return false;
259
+ }
260
+
261
+ return true;
262
+ },
263
+
264
+
265
+ _parse: function() {
266
+ var aliases = CronTime.aliases,
267
+ source = this.source.replace(/[a-z]{1,3}/ig, function(alias) {
268
+ alias = alias.toLowerCase();
269
+
270
+ if (alias in aliases) {
271
+ return aliases[alias];
272
+ }
273
+
274
+ throw new Error('Unknown alias: ' + alias);
275
+ }),
276
+ split = source.replace(/^\s\s*|\s\s*$/g, '').split(/\s+/),
277
+ cur, i = 0,
278
+ len = timeUnits.length;
279
+
280
+ for (; i < timeUnits.length; i++) {
281
+ // If the split source string doesn't contain all digits,
282
+ // assume defaults for first n missing digits.
283
+ // This adds support for 5-digit standard cron syntax
284
+ cur = split[i - (len - split.length)] || CronTime.parseDefaults[i];
285
+ this._parseField(cur, timeUnits[i], CronTime.constraints[i]);
286
+ }
287
+ },
288
+
289
+ _parseField: function(field, type, constraints) {
290
+ var rangePattern = /^(\d+)(?:-(\d+))?(?:\/(\d+))?$/g,
291
+ typeObj = this[type],
292
+ diff, pointer,
293
+ low = constraints[0],
294
+ high = constraints[1];
295
+
296
+ // * is a shortcut to [lower-upper] range
297
+ field = field.replace(/\*/g, low + '-' + high);
298
+
299
+ //commas separate information, so split based on those
300
+ var allRanges = field.split(',');
301
+
302
+ for (var i = 0; i < allRanges.length; i++) {
303
+ if (allRanges[i].match(rangePattern)) {
304
+ allRanges[i].replace(rangePattern, function($0, lower, upper, step) {
305
+ step = parseInt(step) || 1;
306
+ // Positive integer higher than constraints[0]
307
+ lower = Math.min(Math.max(low, ~~Math.abs(lower)), high);
308
+
309
+ // Positive integer lower than constraints[1]
310
+ upper = upper ? Math.min(high, ~~Math.abs(upper)) : lower;
311
+
312
+ // Count from the lower barrier to the upper
313
+ pointer = lower;
314
+
315
+ do {
316
+ typeObj[pointer] = true
317
+ pointer += step;
318
+ } while (pointer <= upper);
319
+ });
320
+ } else {
321
+ throw new Error('Field (' + field + ') cannot be parsed');
322
+ }
323
+ }
324
+ }
294
325
  };
295
326
 
327
+ function command2function(cmd) {
328
+ switch (typeof cmd) {
329
+ case 'string':
330
+ var args = cmd.split(' ');
331
+ var command = args.shift();
332
+
333
+ cmd = spawn.bind(undefined, command, args);
334
+ break;
335
+ case 'object':
336
+ var command = cmd && cmd.command;
337
+ if (command) {
338
+ var args = cmd.args;
339
+ var options = cmd.options;
340
+
341
+ cmd = spawn.bind(undefined, command, args, options);
342
+ }
343
+ break;
344
+ }
345
+
346
+ return cmd
347
+ }
296
348
 
349
+ function CronJob(cronTime, onTick, onComplete, startNow, timeZone, context) {
350
+ if (typeof cronTime != "string" && arguments.length == 1) {
351
+ //crontime is an object...
352
+ onTick = cronTime.onTick;
353
+ onComplete = cronTime.onComplete;
354
+ context = cronTime.context;
355
+ startNow = cronTime.start || cronTime.startNow;
356
+ timeZone = cronTime.timeZone;
357
+ cronTime = cronTime.cronTime;
358
+ }
297
359
 
298
- function CronJob(cronTime, onTick, onComplete, start, timeZone, context) {
299
- if (typeof cronTime != "string" && arguments.length == 1) {
300
- //crontime is an object...
301
- onTick = cronTime.onTick;
302
- onComplete = cronTime.onComplete;
303
- context = cronTime.context;
304
- start = cronTime.start;
305
- timeZone = cronTime.timeZone;
306
- cronTime = cronTime.cronTime;
307
- }
360
+ this.context = (context || this);
361
+ this._callbacks = [];
362
+ this.onComplete = command2function(onComplete);
363
+ this.cronTime = new CronTime(cronTime, timeZone);
308
364
 
309
- if (timeZone && !loadedTimeModule) console.log('You specified a Timezone but have not included the `time` module. Timezone functionality is disabled. Please install the `time` module to use Timezones in your application.');
365
+ addCallback.call(this, command2function(onTick));
310
366
 
311
- this.context = (context || this);
312
- this._callbacks = [];
313
- this.onComplete = onComplete;
314
- this.cronTime = new CronTime(cronTime, timeZone);
367
+ if (startNow) start.call(this);
315
368
 
316
- this.addCallback(onTick);
369
+ return this;
370
+ }
317
371
 
318
- if (start) this.start();
372
+ var addCallback = function(callback) {
373
+ if (typeof callback == 'function') this._callbacks.push(callback);
374
+ }
375
+ CronJob.prototype.addCallback = addCallback;
319
376
 
320
- return this;
377
+ CronJob.prototype.setTime = function(time) {
378
+ if (!(time instanceof CronTime)) throw '\'time\' must be an instance of CronTime.';
379
+ this.stop();
380
+ this.cronTime = time;
321
381
  }
322
382
 
323
- CronJob.prototype = {
324
- /**
325
- * Add a method to fire onTick
326
- */
327
- addCallback: function(callback) {
328
- //only functions
329
- if (typeof callback == 'function') this._callbacks.push(callback);
330
- },
331
-
332
- /**
333
- * Fire all callbacks registered.
334
- */
335
- _callback: function() {
336
- for (var i = (this._callbacks.length - 1); i >= 0; i--) {
337
-
338
- //send this so the callback can call this.stop();
339
- this._callbacks[i].call(this.context, this.onComplete);
340
- }
341
- },
342
-
343
- /**
344
- * Manually set the time of a job
345
- */
346
- setTime: function(time) {
347
- if (!(time instanceof CronTime)) throw '\'time\' must be an instance of CronTime.';
348
- this.stop();
349
- this.cronTime = time;
350
- },
351
-
352
- /**
353
- * Return the next scheduled date for a job
354
- */
355
- nextDate: function() {
356
- return this.cronTime.sendAt();
357
- },
358
-
359
- /**
360
- * Start the cronjob.
361
- */
362
- start: function() {
363
- if (this.running) return;
364
-
365
- var MAXDELAY = 2147483647; // The maximum number of milliseconds setTimeout will wait.
366
- var self = this;
367
- var timeout = this.cronTime.getTimeout();
368
- var remaining = 0;
369
-
370
- if (this.cronTime.realDate) this.runOnce = true;
371
-
372
- // The callback wrapper checks if it needs to sleep another period or not
373
- // and does the real callback logic when it's time.
374
-
375
- function callbackWrapper() {
376
-
377
- // If there is sleep time remaining, calculate how long and go to sleep
378
- // again. This processing might make us miss the deadline by a few ms
379
- // times the number of sleep sessions. Given a MAXDELAY of almost a
380
- // month, this should be no issue.
381
-
382
- if (remaining) {
383
- if (remaining > MAXDELAY) {
384
- remaining -= MAXDELAY;
385
- timeout = MAXDELAY;
386
- } else {
387
- timeout = remaining;
388
- remaining = 0;
389
- }
390
-
391
- self._timeout = setTimeout(callbackWrapper, timeout);
392
- } else {
393
-
394
- // We have arrived at the correct point in time.
395
-
396
- self.running = false;
397
-
398
- //start before calling back so the callbacks have the ability to stop the cron job
399
- if (!(self.runOnce)) self.start();
400
-
401
- self._callback();
402
- }
403
- }
404
-
405
- if (timeout >= 0) {
406
- this.running = true;
407
-
408
- // Don't try to sleep more than MAXDELAY ms at a time.
409
-
410
- if (timeout > MAXDELAY) {
411
- remaining = timeout - MAXDELAY;
412
- timeout = MAXDELAY;
413
- }
414
-
415
- this._timeout = setTimeout(callbackWrapper, timeout);
416
- } else {
417
- this.stop();
383
+ CronJob.prototype.nextDate = function() {
384
+ return this.cronTime.sendAt();
385
+ }
386
+
387
+ var start = function() {
388
+ if (this.running) return;
389
+
390
+ var MAXDELAY = 2147483647; // The maximum number of milliseconds setTimeout will wait.
391
+ var self = this;
392
+ var timeout = this.cronTime.getTimeout();
393
+ var remaining = 0;
394
+
395
+ if (this.cronTime.realDate) this.runOnce = true;
396
+
397
+ // The callback wrapper checks if it needs to sleep another period or not
398
+ // and does the real callback logic when it's time.
399
+
400
+ function callbackWrapper() {
401
+
402
+ // If there is sleep time remaining, calculate how long and go to sleep
403
+ // again. This processing might make us miss the deadline by a few ms
404
+ // times the number of sleep sessions. Given a MAXDELAY of almost a
405
+ // month, this should be no issue.
406
+
407
+ if (remaining) {
408
+ if (remaining > MAXDELAY) {
409
+ remaining -= MAXDELAY;
410
+ timeout = MAXDELAY;
411
+ } else {
412
+ timeout = remaining;
413
+ remaining = 0;
414
+ }
415
+
416
+ self._timeout = setTimeout(callbackWrapper, timeout);
417
+ } else {
418
+
419
+ // We have arrived at the correct point in time.
420
+
421
+ self.running = false;
422
+
423
+ //start before calling back so the callbacks have the ability to stop the cron job
424
+ if (!(self.runOnce)) self.start();
425
+
426
+ for (var i = (self._callbacks.length - 1); i >= 0; i--)
427
+ self._callbacks[i].call(self.context, self.onComplete);
418
428
  }
419
- },
420
-
421
- /**
422
- * Stop the cronjob.
423
- */
424
- stop: function() {
425
- if (this._timeout)
426
- clearTimeout(this._timeout);
427
- this.running = false;
428
- if (this.onComplete) this.onComplete();
429
- }
430
- };
429
+ }
430
+
431
+ if (timeout >= 0) {
432
+ this.running = true;
433
+
434
+ // Don't try to sleep more than MAXDELAY ms at a time.
435
+
436
+ if (timeout > MAXDELAY) {
437
+ remaining = timeout - MAXDELAY;
438
+ timeout = MAXDELAY;
439
+ }
440
+
441
+ this._timeout = setTimeout(callbackWrapper, timeout);
442
+ } else {
443
+ this.stop();
444
+ }
445
+ }
446
+
447
+ CronJob.prototype.start = start;
448
+
449
+ /**
450
+ * Stop the cronjob.
451
+ */
452
+ CronJob.prototype.stop = function() {
453
+ if (this._timeout)
454
+ clearTimeout(this._timeout);
455
+ this.running = false;
456
+ if (typeof this.onComplete == 'function') this.onComplete();
457
+ }
431
458
 
432
459
  if (exports) {
433
- exports.job = function(cronTime, onTick, onComplete) {
434
- return new CronJob(cronTime, onTick, onComplete);
435
- }
460
+ exports.job = function(cronTime, onTick, onComplete) {
461
+ return new CronJob(cronTime, onTick, onComplete);
462
+ }
436
463
 
437
- exports.time = function(cronTime, timeZone) {
438
- return new CronTime(cronTime, timeZone);
439
- }
464
+ exports.time = function(cronTime, timeZone) {
465
+ return new CronTime(cronTime, timeZone);
466
+ }
440
467
 
441
- exports.sendAt = function(cronTime) {
442
- return exports.time(cronTime).sendAt();
443
- }
468
+ exports.sendAt = function(cronTime) {
469
+ return exports.time(cronTime).sendAt();
470
+ }
444
471
 
445
- exports.timeout = function(cronTime) {
446
- return exports.time(cronTime).getTimeout();
447
- }
472
+ exports.timeout = function(cronTime) {
473
+ return exports.time(cronTime).getTimeout();
474
+ }
448
475
 
449
- exports.CronJob = CronJob;
450
- exports.CronTime = CronTime;
476
+ exports.CronJob = CronJob;
477
+ exports.CronTime = CronTime;
451
478
  }