Skip to content

Commit ce54f4d

Browse files
authored
Update bug fixes - fix lost context in helper functions (#38)
* started bug fix for [issue #37](#37) * Just commiting what I have which is borked. * finally fixed undefined ref exception. * Fixed tests * test update tab as well * Removed unecessary files * add back the original update tests * bugfixes: * start / stop workflow for update fixed. * preserved additional options. * Don't need to preserve start options. preserved in job.
1 parent 2e9268f commit ce54f4d

File tree

5 files changed

+78
-28
lines changed

5 files changed

+78
-28
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ node_modules*
44
*.ipr
55
*.iws
66
*.suo
7-
.vs
7+
.vs*

.vscode/settings.json

Lines changed: 0 additions & 3 deletions
This file was deleted.

lib/crontab_manager.js

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,19 @@
2222
*/
2323

2424
var CronJob = require('cron').CronJob;
25+
var cronJobOptionalKeys = [
26+
"cronTime", //this preserves the crontab itself, timeZone, utcOffset.
27+
"context",
28+
"unrefTimeout",
29+
"onComplete"
30+
]
2531

2632
function CrontabManager(key, tab, task, options) {
2733
this.jobs = {};
2834
if (key && tab && task) {
2935
this.add(key, tab, task, options);
3036
}
37+
return this
3138
}
3239

3340
CrontabManager.prototype.add = function (key, tab, task, options) {
@@ -129,20 +136,14 @@ CrontabManager.prototype.stopAll = function () {
129136
CrontabManager.prototype.toString = function () {
130137
var manString = "{\n";
131138
for (jobKey in this.jobs) {
132-
manString += `'${jobKey}': ${this.jobs[jobKey].cronTime.source}: ${this.jobs[jobKey]._callbacks[0]}: ${this.jobs[jobKey].running ? "Running" : "Stopped"}`
139+
manString += `'${jobKey}': ${this.jobs[jobKey].cronTime.source}: ${this.jobs[jobKey]._callbacks[0]}: ${this.jobs[jobKey].running ? "Running" : "Stopped"}\n`
133140
}
134-
manString += "\n}";
141+
manString += "}";
135142
return manString;
136143
}
137144

138-
CrontabManager.prototype.listCrons = function () {
139-
var manString = "{\n";
140-
for (jobKey in this.jobs) {
141-
manString += `'${jobKey}': ${this.jobs[jobKey].cronTime.source} status: ${this.jobs[jobKey].running ? "Running" : "Stopped"} \n`;
142-
}
143-
manString += "\n}";
144-
return manString;
145-
}
145+
CrontabManager.prototype.listCrons = CrontabManager.prototype.toString
146+
146147

147148
CrontabManager.prototype.exists = function (tabKey) {
148149
if (this.jobs[tabKey]) {
@@ -175,7 +176,9 @@ function updateTab(key, cronstring) {
175176
var running = this.jobs[key].running;
176177
this.jobs[key].stop()
177178
if (typeof cronstring === 'string' || cronstring instanceof Date) {
178-
this.jobs[key] = new CronJob(cronstring, this.jobs[key]._callbacks[0], this.jobs[key].onComplete, running, this.jobs[key].zone)
179+
var preservedOptions = getAdditionalOptions.call(this, key)
180+
this.jobs[key] = new CronJob(combineOptions(cronstring, this.jobs[key]._callbacks[0], preservedOptions))
181+
if (running) this.jobs[key].start()
179182
} else {
180183
throw new Error(`The cron definition passed was not a string or a Date object! ${key} was stopped and not updated`);
181184
}
@@ -187,15 +190,37 @@ function updateTab(key, cronstring) {
187190
function updateTask(key, task) {
188191
try {
189192
var running = this.jobs[key].running;
190-
this.jobs[key].stop()
193+
if (running) this.jobs[key].stop()
191194
if (!(task instanceof Function)) {
192195
console.error(`can't update with something that is not a function: ${typeof(task)}`)
193196
return
194197
}
195-
this.jobs[key] = new CronJob(this.jobs[key].cronTime.source, task, this.jobs[key].onComplete, running, this.jobs[key].zone)
198+
var preservedOptions = getAdditionalOptions.call(this, key)
199+
this.jobs[key] = new CronJob(combineOptions(this.jobs[key].cronTime.source, task, preservedOptions))
200+
if (running) this.jobs[key].start()
196201
} catch (tabErr) {
197202
console.error(`error updating task: ${key} - ${tabErr.message}`);
198203
}
199204
}
200205

206+
function getAdditionalOptions(key) {
207+
var additionalOptions = {}
208+
var job = this.jobs[key]
209+
function getOptionsFromCronTime() {
210+
if (job.cronTime) {
211+
additionalOptions.timeZone =job.cronTime.timeZone
212+
additionalOptions.utcOffset = job.cronTime.utcOffset
213+
additionalOptions.start = job.cronTime.start || job.cronTime.startJob || job.cronTime.startNow
214+
}
215+
216+
}
217+
cronJobOptionalKeys.forEach((key) => {
218+
if (key === "cronTime") getOptionsFromCronTime()
219+
else additionalOptions[key] = job[key]
220+
})
221+
return additionalOptions
222+
223+
}
224+
225+
201226
module.exports = CrontabManager;

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "cron-job-manager",
3-
"version": "2.2.1",
3+
"version": "2.3.0",
44
"description": "A wrapper Object for node-cron that allows you to manage multiple cron jobs at once.",
55
"author": "Carl Yamamoto-Furst",
66
"main": "lib/crontab_manager.js",

tests/update.js

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,59 @@ const CronJobManager = require('../lib/crontab_manager'),
55
cronTab = new CronJobManager();
66

77
exports.test = () => {
8-
let currDate = new Date();
8+
let currDate = new Date();
99
cronTab.add('updateTest', currDate, () => {console.log("update Cron... wooo!")});
10+
1011
//update the tab - string
1112
let tabString = '0 */2 * * * *';
1213
cronTab.update('updateTest', tabString);
1314
console.assert(/0 \*\/2 \* \* \* \*/.test(cronTab), `Could not find updated crontab String! ${cronTab}`);
14-
15+
1516
//update the tab - Date;
1617
let testDate = new Date('2018-08-24T09:57:22-0400');
1718
cronTab.update('updateTest', testDate);
1819
console.assert(/Fri Aug 24 2018 09\:57\:22 GMT-0400/.test(cronTab), `Could not find updated Crontab date! ${cronTab}`);
19-
20+
2021
//update the task
2122
let newFunc = function() {
22-
23+
2324
console.log("you can now doo a double wooo... wooo wooo....");
2425
}
25-
26+
2627
cronTab.update('updateTest', newFunc);
27-
console.assert(`${cronTab}`.search("double wooo"), "coulnd't the update task when updating just the task!");
28-
28+
console.assert(`${cronTab}`.search("double wooo") !== -1, "coulnd't the update task when updating just the task!");
29+
2930
//update the tab and the task - we know the update tab works. We just need to make sure the task gets updated.
3031
cronTab.update('updateTest', testDate, () => {console.log("A New Task!")});
31-
32-
console.assert(`${cronTab}`.search("A New Task!"), "could't find the updated task when updating tab and task!");
32+
33+
console.assert(`${cronTab}`.search("A New Task!") !== -1, "could't find the updated task when updating tab and task!");
34+
35+
let thirtyOne = 31
36+
cronTab.add(thirtyOne.toString(),new Date(), () => {console.log("new Job...")})
37+
cronTab.update(thirtyOne.toString(), new Date(), () => {console.log("updated 31...")})
38+
39+
console.assert(`${cronTab}`.search("updated 31...") !== -1, "couldn't the update task when updating a task with a number literal coerced to string.");
40+
41+
let additionalOptions = {utcOffset: "-5", onComplete: () => {console.log("I'm done working")},start: true}
3342

43+
function testAdditionalOptions() {
44+
[
45+
"cronTime",
46+
"context",
47+
"onComplete",
48+
"unrefTimeout",
49+
"start"
50+
].forEach( (key) => {
51+
if (key === "cronTime" && cronTab.jobs["test update with additional"][key] !== undefined && cronTab.jobs["test update with additional"][key].hasOwnProperty('utcOffset')) console.assert(cronTab.jobs["test update with additional"][key].utcOffset === additionalOptions.utcOffset, `${key} did not pass jobs value: ${cronTab.jobs["test update with additional"][key].utcOffset} additionalOptions: ${additionalOptions.utcOffset}`)
52+
else if (key ==="start" && ! (cronTab.jobs["test update with additional"].hasOwnProperty("running") && cronTab.jobs["test update with additional"].running)) console.assert(false, "Started Job did not restart after update!")
53+
else if (cronTab.jobs["test update with additional"].hasOwnProperty(key) && additionalOptions.hasOwnProperty(key)) console.assert(cronTab.jobs["test update with additional"][key] === additionalOptions[key], `${key} did not pass: jobs value: ${cronTab.jobs["test update with additional"][key]}, additionalOptions valud: ${additionalOptions[key]}`)
54+
})
55+
}
56+
cronTab.add("test update with additional", "* * * * * *", () => {console.log("shhh.. I'm working!")}, additionalOptions )
57+
cronTab.update("test update with additional", () => {console.log("shh... I'm still working!")});
58+
testAdditionalOptions()
59+
cronTab.update("test update with additional", "*/2 * * * * *")
60+
testAdditionalOptions()
61+
cronTab.stopAll()
3462

35-
};
63+
};

0 commit comments

Comments
 (0)