cron 1.4.0 → 1.6.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/README.md CHANGED
@@ -50,7 +50,7 @@ new CronJob('* * * * * *', function() {
50
50
  }, null, true, 'America/Los_Angeles');
51
51
  ```
52
52
 
53
- Note - You need to explictly start a job in order to make it run. This gives a
53
+ Note - You need to explicitly start a job in order to make it run. This gives a
54
54
  little more control over running your jobs.
55
55
 
56
56
  There are more examples available in this repository at:
@@ -69,9 +69,10 @@ link have five fields, and 1 minute as the finest granularity, but this library
69
69
  has six fields, with 1 second as the finest granularity.
70
70
 
71
71
  There are tools that help when constructing your cronjobs. You might find
72
- something like https://cronjob.xyz/ helpful. But, note that it doesn't accept
73
- the exact same syntax as this library, for instance, it doesn't accept the
74
- `seconds` field, so keep that in mind.
72
+ something like https://crontab.guru/ or https://cronjob.xyz/ helpful. But,
73
+ note that these don't necessarily accept the exact same syntax as this
74
+ library, for instance, it doesn't accept the `seconds` field, so keep that in
75
+ mind.
75
76
 
76
77
 
77
78
  Cron Ranges
@@ -89,6 +90,26 @@ week where both 0 and 7 represent Sunday. We do not.
89
90
  * Day of Week: 0-6 (Sun-Sat)
90
91
 
91
92
 
93
+ Gotchas
94
+ ==
95
+
96
+ * Millisecond level granularity in JS or moment date objects.
97
+ Because computers take time to do things, there may be some delay in execution.
98
+ This should be on the order of milliseconds. This module doesn't allow MS level
99
+ granularity for the regular cron syntax, but _does_ allow you to specify a real
100
+ date of execution in either a javascript date object or a moment object.
101
+ When this happens you may find that you aren't able to execute a job that
102
+ _should_ run in the future like with `new Date().setMilliseconds(new
103
+ Date().getMilliseconds() + 1)`. This is due to those cycles of execution
104
+ above. This wont be the same for everyone because of compute speed. When I
105
+ tried it locally I saw that somewhere around the 4-5 ms mark was where I got
106
+ consistent ticks using real dates, but anything less than that would result
107
+ in an exception. This could be really confusing. We could restrict the
108
+ granularity for all dates to seconds, but felt that it wasn't a huge problem
109
+ so long as you were made aware. If this becomes more of an issue, We can
110
+ revisit it.
111
+
112
+
92
113
  API
93
114
  ==
94
115
 
@@ -0,0 +1,9 @@
1
+ const CronJob = require('../lib/cron.js').CronJob;
2
+
3
+ console.log('Before job instantiation');
4
+ const job = new CronJob('* 4-22 * * 1-5', function() {
5
+ const d = new Date();
6
+ console.log('Every Minute Between hours 4-22, Monday through Friday:', d);
7
+ });
8
+ console.log('After job instantiation');
9
+ job.start();
@@ -1,7 +1,7 @@
1
1
  const CronJob = require('../lib/cron.js').CronJob;
2
2
 
3
3
  console.log('Before job instantiation');
4
- const job = new CronJob('* */10 * * * *', function() {
4
+ const job = new CronJob('0 */10 * * * *', function() {
5
5
  const d = new Date();
6
6
  console.log('Every Tenth Minute:', d);
7
7
  });
@@ -1,7 +1,7 @@
1
1
  const CronJob = require('../lib/cron.js').CronJob;
2
2
 
3
3
  console.log('Before job instantiation');
4
- const job = new CronJob('* */30 9-17 * * *', function() {
4
+ const job = new CronJob('0 */30 9-17 * * *', function() {
5
5
  const d = new Date();
6
6
  console.log('Every 30 minutes between 9-17:', d);
7
7
  });
@@ -0,0 +1,24 @@
1
+ const CronJob = require('../lib/cron.js').CronJob;
2
+
3
+ const job = new CronJob(
4
+ '0 * * * * *',
5
+ function() {
6
+ console.log('Date: ', new Date());
7
+ },
8
+ null,
9
+ true
10
+ );
11
+
12
+ console.log('System TZ next 5: ', job.nextDates(5));
13
+
14
+ const jobUTC = new CronJob(
15
+ '0 * * * * *',
16
+ function() {
17
+ console.log('Date: ', new Date());
18
+ },
19
+ null,
20
+ true,
21
+ 'UTC'
22
+ );
23
+
24
+ console.log('UTC next 5: ', jobUTC.nextDates(5));
@@ -0,0 +1,19 @@
1
+ const CronJob = require('../lib/cron.js').CronJob;
2
+
3
+ // XXX: SEE README GOTCHAS ABOUT WHY THIS COULD BE IN THE PAST!
4
+ let d = new Date();
5
+ d.setMilliseconds(d.getMilliseconds() + 1);
6
+
7
+ console.log('Before job instantiation');
8
+ const job = new CronJob(
9
+ d,
10
+ () => {
11
+ const d2 = new Date();
12
+ console.log('Tick @:', d2);
13
+ },
14
+ () => {
15
+ console.log('complete');
16
+ }
17
+ );
18
+ console.log('After job instantiation');
19
+ job.start();
@@ -0,0 +1,15 @@
1
+ const CronJob = require('../lib/cron.js').CronJob;
2
+
3
+ console.log('Before job instantiation');
4
+ const job = new CronJob('*/5 * * * * *', function() {
5
+ const d = new Date();
6
+ console.log('First:', d);
7
+ });
8
+
9
+ const job2 = new CronJob('*/8 * * * * *', function() {
10
+ const d = new Date();
11
+ console.log('Second:', d);
12
+ });
13
+ console.log('After job instantiation');
14
+ job.start();
15
+ job2.start();
@@ -0,0 +1,13 @@
1
+ const CronJob = require('../lib/cron.js').CronJob;
2
+
3
+ console.log('first');
4
+ const job = new CronJob(
5
+ '0 0 9 4 * *',
6
+ function() {
7
+ console.log('message');
8
+ },
9
+ null,
10
+ true,
11
+ 'America/Sao_Paulo'
12
+ );
13
+ console.log('second');
package/lib/cron.js CHANGED
@@ -32,7 +32,7 @@
32
32
  this.zone = zone;
33
33
  }
34
34
 
35
- if (utcOffset) this.utcOffset = utcOffset;
35
+ if (typeof utcOffset !== 'undefined') this.utcOffset = utcOffset;
36
36
 
37
37
  var that = this;
38
38
  timeUnits.map(function(timeUnit) {
@@ -89,27 +89,43 @@
89
89
  CronTime.prototype = {
90
90
  _verifyParse: function() {
91
91
  var months = Object.keys(this.month);
92
+ var ok = false;
92
93
 
94
+ /* if a dayOfMonth is not found in all months, we only need to fix the last
95
+ wrong month to prevent infinite loop */
96
+ var lastWrongMonth = {};
93
97
  for (var i = 0; i < months.length; i++) {
94
98
  var m = months[i];
95
99
  var con = CronTime.monthConstraints[parseInt(m, 10)];
96
- var ok = false;
97
100
  var dsom = Object.keys(this.dayOfMonth);
98
101
 
99
102
  for (var j = 0; j < dsom.length; j++) {
100
103
  var dom = dsom[j];
101
104
  if (dom <= con) {
102
105
  ok = true;
103
- } else {
104
- delete this.dayOfMonth[j];
105
- this.dayOfMonth[String(Number(dsom[j])) % con] = true;
106
106
  }
107
107
  }
108
108
 
109
109
  if (!ok) {
110
+ // save the month in order to be fixed if all months fails (infinite loop)
111
+ lastWrongMonth = m;
110
112
  console.warn("Month '" + m + "' is limited to '" + con + "' days.");
111
113
  }
112
114
  }
115
+
116
+ // infinite loop detected (dayOfMonth is not found in all months)
117
+ if (!ok) {
118
+ var con = CronTime.monthConstraints[parseInt(lastWrongMonth, 10)];
119
+ var dsom = Object.keys(this.dayOfMonth);
120
+ for (var k = 0; k < dsom.length; k++) {
121
+ var dom = dsom[k];
122
+ if (dom > con) {
123
+ delete this.dayOfMonth[dom];
124
+ var fixedDay = Number(dom) % con;
125
+ this.dayOfMonth[fixedDay] = true;
126
+ }
127
+ }
128
+ }
113
129
  },
114
130
 
115
131
  /**
@@ -122,11 +138,16 @@
122
138
  date = date.tz(this.zone);
123
139
  }
124
140
 
125
- if (this.utcOffset) {
141
+ if (typeof this.utcOffset !== 'undefined') {
126
142
  date = date.utcOffset(this.utcOffset);
127
143
  }
128
144
 
129
145
  if (this.realDate) {
146
+ const diff = moment().diff(date);
147
+ if (diff > 0) {
148
+ throw new Error('WARNING: Date in past. Will never be fired.');
149
+ }
150
+
130
151
  return date;
131
152
  }
132
153
 
@@ -174,7 +195,6 @@
174
195
  /**
175
196
  * get next date that matches parsed cron time
176
197
  */
177
-
178
198
  _getNextDateFrom: function(start, zone) {
179
199
  var date;
180
200
  var firstDate = moment(start).valueOf();
@@ -198,35 +218,54 @@
198
218
  throw new Error('ERROR: You specified an invalid date.');
199
219
  }
200
220
 
201
- if (this.realDate && start < new Date()) {
202
- throw new Error('WARNING: Date in past. Will never be fired.');
203
- }
204
-
205
- if (this.realDate) {
206
- return date;
207
- }
208
-
209
- // sanity check
221
+ // it shouldn't take more than 5 seconds to find the next execution time
222
+ // being very generous with this. Throw error if it takes too long to find the next time to protect from
223
+ // infinite loop.
224
+ var finding = true;
225
+ var findingTimeout = setTimeout(function() {
226
+ finding = false;
227
+ }, 5000);
228
+ // determine next date
210
229
  while (true) {
211
230
  var diff = date - start;
231
+ var prevMonth = date.month();
232
+ var prevDay = date.days();
233
+ var prevMinute = date.minutes();
234
+ var prevSeconds = date.seconds();
212
235
  var origDate = new Date(date);
213
236
 
237
+ if (!finding) {
238
+ throw new Error(
239
+ `Something went wrong. cron reached maximum iterations.
240
+ Please open an issue (https://github.com/kelektiv/node-cron/issues/new) and provide the following string
241
+ Time Zone: ${zone || '""'} - Cron String: ${this} - UTC offset: ${date.format(
242
+ 'Z'
243
+ )} - current Date: ${moment().toString()}`
244
+ );
245
+ }
214
246
  if (
215
247
  !(date.month() in this.month) &&
216
248
  Object.keys(this.month).length !== 12
217
249
  ) {
218
250
  date.add(1, 'M');
251
+ if (date.month() === prevMonth) {
252
+ date.add(1, 'M');
253
+ }
219
254
  date.date(1);
220
255
  date.hours(0);
221
256
  date.minutes(0);
222
257
  date.seconds(0);
223
258
  continue;
224
259
  }
260
+
225
261
  if (
226
262
  !(date.date() in this.dayOfMonth) &&
227
263
  Object.keys(this.dayOfMonth).length !== 31
228
264
  ) {
229
265
  date.add(1, 'd');
266
+ if (date.days() === prevDay) {
267
+ date.add(1, 'd');
268
+ }
230
269
  date.hours(0);
231
270
  date.minutes(0);
232
271
  date.seconds(0);
@@ -238,6 +277,9 @@
238
277
  Object.keys(this.dayOfWeek).length !== 7
239
278
  ) {
240
279
  date.add(1, 'd');
280
+ if (date.days() === prevDay) {
281
+ date.add(1, 'd');
282
+ }
241
283
  date.hours(0);
242
284
  date.minutes(0);
243
285
  date.seconds(0);
@@ -246,13 +288,14 @@
246
288
  }
247
289
  continue;
248
290
  }
291
+
249
292
  if (
250
293
  !(date.hours() in this.hour) &&
251
294
  Object.keys(this.hour).length !== 24
252
295
  ) {
253
296
  origDate = moment(date);
254
297
  date.hours(
255
- date.hours() == 23 && diff > 86400000 ? 0 : date.hours() + 1
298
+ date.hours() === 23 && diff > 86400000 ? 0 : date.hours() + 1
256
299
  );
257
300
  date.minutes(0);
258
301
  date.seconds(0);
@@ -261,6 +304,7 @@
261
304
  }
262
305
  continue;
263
306
  }
307
+
264
308
  if (
265
309
  !(date.minutes() in this.minute) &&
266
310
  Object.keys(this.minute).length !== 60
@@ -277,6 +321,7 @@
277
321
  }
278
322
  continue;
279
323
  }
324
+
280
325
  if (
281
326
  !(date.seconds() in this.second) &&
282
327
  Object.keys(this.second).length !== 60
@@ -299,6 +344,7 @@
299
344
  break;
300
345
  }
301
346
 
347
+ clearTimeout(findingTimeout);
302
348
  return date;
303
349
  },
304
350
 
@@ -307,7 +353,8 @@
307
353
  */
308
354
  _findDST: function(date) {
309
355
  var newDate = moment(date);
310
- while (newDate <= date) { // eslint seems to trigger here, it is wrong
356
+ while (newDate <= date) {
357
+ // eslint seems to trigger here, it is wrong
311
358
  newDate.add(1, 's');
312
359
  }
313
360
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cron",
3
3
  "description": "Cron jobs for your node",
4
- "version": "1.4.0",
4
+ "version": "1.6.0",
5
5
  "author": "Nick Campbell <nicholas.j.campbell@gmail.com> (http://github.com/ncb000gt)",
6
6
  "bugs": {
7
7
  "url": "http://github.com/kelektiv/node-cron/issues"
@@ -3,6 +3,8 @@ var expect = chai.expect;
3
3
  var sinon = require('sinon');
4
4
  var cron = require('../lib/cron');
5
5
 
6
+ /* eslint-disable no-new */
7
+
6
8
  describe('cron', function() {
7
9
  it('should run every second (* * * * * *)', function() {
8
10
  var clock = sinon.useFakeTimers();
@@ -544,7 +546,7 @@ describe('cron', function() {
544
546
 
545
547
  it('should test if timezone is valid.', function() {
546
548
  expect(function() {
547
- new cron.CronJob({ // ignore eslint error here
549
+ new cron.CronJob({
548
550
  cronTime: '* * * * * *',
549
551
  onTick: function() {},
550
552
  timeZone: 'fake/timezone'
@@ -896,6 +898,28 @@ describe('cron', function() {
896
898
  expect(c).to.eql(8);
897
899
  });
898
900
 
901
+ // from https://github.com/kelektiv/node-cron/issues/180#issuecomment-154108131
902
+ it('should run once not double', function() {
903
+ var c = 0;
904
+ var d = new Date(2015, 1, 1, 1, 1, 41, 0);
905
+ var clock = sinon.useFakeTimers(d.getTime());
906
+
907
+ var job = new cron.CronJob({
908
+ cronTime: '* * * * *',
909
+ onTick: function() {
910
+ c++;
911
+ },
912
+ start: true
913
+ });
914
+
915
+ var minute = 60 * 1000;
916
+ clock.tick(minute);
917
+ expect(c).to.eql(1);
918
+ clock.restore();
919
+ job.stop();
920
+ expect(c).to.eql(1);
921
+ });
922
+
899
923
  it('should run every second monday');
900
924
 
901
925
  describe('with utcOffset', function() {
@@ -1,8 +1,10 @@
1
1
  var chai = require('chai');
2
2
  var expect = chai.expect;
3
3
  var cron = require('../lib/cron');
4
+ var moment = require('moment-timezone');
5
+ var sinon = require('sinon');
4
6
 
5
- // most eslint errors here are due to side effects. i don't care much about them right now
7
+ /* eslint-disable no-new */
6
8
 
7
9
  describe('crontime', function() {
8
10
  it('should test stars (* * * * * *)', function() {
@@ -168,13 +170,18 @@ describe('crontime', function() {
168
170
  });
169
171
 
170
172
  it('should test next real date', function() {
171
- var ct = new cron.CronTime(new Date());
173
+ var initialDate = new Date()
174
+ var ct = new cron.CronTime(initialDate);
172
175
 
173
176
  var nextDate = new Date();
174
177
  nextDate.setMonth(nextDate.getMonth() + 1);
175
178
  expect(nextDate).to.be.gt(ct.source._d);
176
- var nextdt = ct._getNextDateFrom(nextDate);
177
- expect(nextdt.isSame(nextDate)).to.be.true;
179
+ var nextdt = ct.sendAt(0);
180
+ // there shouldn't be a "next date" when using a real date.
181
+ // execution happens once
182
+ // so the return should be the date passed in unless explicitly reset
183
+ expect(nextdt.isBefore(nextDate)).to.be.true;
184
+ expect(nextdt.isSame(initialDate)).to.be.true;
178
185
  });
179
186
 
180
187
  it('should test next month selection');
@@ -226,7 +233,68 @@ describe('crontime', function() {
226
233
  previousDate = nextDate;
227
234
  }
228
235
  });
236
+ it('should work around time zone changes that shifts time back (1)',function(){
237
+ var d = new Date("10-7-2018")
238
+ // America/Sao_Paulo has a time zone change around NOV 3 2018.
239
+ var cronTime = new cron.CronTime('0 0 9 4 * *');
240
+ var nextDate = cronTime._getNextDateFrom(d, 'America/Sao_Paulo');
241
+ expect(nextDate.valueOf()).to.equal(moment('2018-11-04T09:00:00.000-02:00').valueOf())
242
+ });
243
+ it('should work around time zone changes that shifts time back (2)',function(){
244
+ // Asia/Amman DST ends in 26 - OCT-2018 (-1 to hours)
245
+ var d = moment.tz('2018-10-25T23:00','Asia/Amman');
246
+ var cronTime = new cron.CronTime('0 0 * * *');
247
+ var nextDate = cronTime._getNextDateFrom(d, 'Asia/Amman');
248
+ expect(nextDate-moment.tz('2018-10-26T00:00','Asia/Amman')).to.equal(0);
249
+ });
250
+ it('should work around time zone changes that shifts time forward',function(){
251
+ // Asia/Amman DST starts in 30-March-2018 (+1 to hours)
252
+ var currentDate = moment.tz('2018-03-29T23:00','Asia/Amman');
253
+ var cronTime = new cron.CronTime('* * * * *');
254
+ for(var i=0;i<100;i++){
255
+ var nextDate = cronTime._getNextDateFrom(currentDate,'Asia/Amman');
256
+ expect(nextDate-currentDate).to.equal(1000*60);
257
+ currentDate=nextDate;
258
+ }
259
+ });
260
+ it('should generate the right N next days for * * * * *',function(){
261
+ var cronTime = new cron.CronTime('* * * * *');
262
+ var currentDate=moment().seconds(0).milliseconds(0);
263
+ for(var i=0;i<100;i++){
264
+ var nextDate = cronTime._getNextDateFrom(currentDate);
265
+ expect(nextDate-currentDate).to.equal(1000*60);
266
+ currentDate=nextDate;
267
+ }
268
+ });
269
+ it('should generate the right N next days for 0 0 9 * * *',function(){
270
+ var cronTime = new cron.CronTime('0 0 9 * * *');
271
+ var currentDate=moment().utc().seconds(0).milliseconds(0).hours(9).minutes(0);
272
+ for(var i=0;i<100;i++){
273
+ var nextDate = cronTime._getNextDateFrom(currentDate);
274
+ expect(nextDate-currentDate).to.equal(1000*60*60*24);
275
+ currentDate=nextDate;
276
+ }
277
+ });
278
+ it('should generate the right N next days for 0 0 * * * with a time zone',function(){
279
+ var cronTime = new cron.CronTime('0 * * * *');
280
+ var currentDate=moment.tz('2018-11-02T23:00','America/Sao_Paulo').seconds(0).milliseconds(0);
281
+ for(var i=0;i<25;i++){
282
+ var nextDate = cronTime._getNextDateFrom(currentDate,'America/Sao_Paulo');
283
+ expect(nextDate-currentDate).to.equal(1000*60*60);
284
+ currentDate=nextDate;
285
+ }
286
+
287
+ });
288
+ it('should generate the right N next days for */3 * * * * with a time zone',function(){
289
+ var cronTime = new cron.CronTime('*/3 * * * *');
290
+ var currentDate=moment.tz('2018-11-02T23:00','America/Sao_Paulo').seconds(0).milliseconds(0);
291
+ for(var i=0;i<25;i++){
292
+ var nextDate = cronTime._getNextDateFrom(currentDate,'America/Sao_Paulo');
293
+ expect(nextDate-currentDate).to.equal(1000*60*3);
294
+ currentDate=nextDate;
295
+ }
229
296
 
297
+ });
230
298
  it('should generete the right next day when cron is set to every 15 min in Feb', function() {
231
299
  var cronTime = new cron.CronTime('*/15 * * FEB *');
232
300
  var previousDate = new Date(Date.UTC(2018, 3, 0, 0, 0));
@@ -235,4 +303,28 @@ describe('crontime', function() {
235
303
  new Date(Date.UTC(2019, 1, 1, 0, 0)).valueOf()
236
304
  );
237
305
  });
306
+
307
+ it('should accept 0 as a valid UTC offset', function() {
308
+ var clock = sinon.useFakeTimers();
309
+
310
+ var cronTime = new cron.CronTime('0 11 * * *', null, 0);
311
+ var expected = moment().add(11, 'hours').unix();
312
+ var actual = cronTime.sendAt().unix();
313
+
314
+ expect(actual).to.equal(expected);
315
+
316
+ clock.restore();
317
+ });
318
+
319
+ it('should accept -120 as a valid UTC offset', function() {
320
+ var clock = sinon.useFakeTimers();
321
+
322
+ var cronTime = new cron.CronTime('0 11 * * *', null, -120);
323
+ var expected = moment().add(13, 'hours').unix();
324
+ var actual = cronTime.sendAt().unix();
325
+
326
+ expect(actual).to.equal(expected);
327
+
328
+ clock.restore();
329
+ });
238
330
  });