Skip to content

Commit

Permalink
Delete a task by reference or by name
Browse files Browse the repository at this point in the history
  • Loading branch information
brian-geoghegan committed Nov 22, 2022
1 parent a0be3f4 commit 7d443b0
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/node-cron.js
Expand Up @@ -61,4 +61,14 @@ function getTasks() {
return storage.getTasks();
}

module.exports = { schedule, validate, getTasks };
/**
* Deletes a scheduled task.
* @param {string || ScheduledTask} task This can be a string of the task Id or the task object itself.
* @returns {ScheduledTask[]} The scheduled tasks.
*/
function deleteTask(task) {
storage.delete(task);
return this.getTasks();
}

module.exports = { schedule, validate, getTasks, deleteTask };
7 changes: 7 additions & 0 deletions src/storage.js
Expand Up @@ -14,6 +14,13 @@ module.exports = (() => {
},
getTasks: () => {
return global.scheduledTasks;
},
delete: (task) => {
if (typeof task === 'string') {
global.scheduledTasks.delete(task);
} else {
global.scheduledTasks.delete(task.options.name);
}
}
};
})();
30 changes: 30 additions & 0 deletions test/node-cron-test.js
Expand Up @@ -69,6 +69,36 @@ describe('node-cron', () => {

assert.equal(0, executed);
});

it('should delete a scheduled task', () => {
const name = 'testId';
let executed = 0;
const task = cron.schedule('* * * * * *', () => {
executed += 1;
}, { scheduled: true, name });

this.clock.tick(2000);

assert.equal(2, executed);
assert.equal(cron.getTasks().get(name), task);
cron.deleteTask(task);
assert.equal(cron.getTasks().get(name), undefined);
});

it('should delete a scheduled task by name', () => {
const name = 'testId';
let executed = 0;
const task = cron.schedule('* * * * * *', () => {
executed += 1;
}, { scheduled: true, name });

this.clock.tick(2000);

assert.equal(2, executed);
assert.equal(cron.getTasks().get(name), task);
cron.deleteTask(name);
assert.equal(cron.getTasks().get(name), undefined);
});

it('should start a stoped task', () => {
let executed = 0;
Expand Down
12 changes: 12 additions & 0 deletions test/storage-test.js
Expand Up @@ -14,6 +14,18 @@ describe('storage', () => {
assert.lengthOf(storage.getTasks(), 1);
});

it('should delete a tasks', () => {
global.scheduledTasks = new Map();
global.scheduledTasks.set('id1', {});
global.scheduledTasks.set('id2', {});
assert.lengthOf(storage.getTasks(), 2);
storage.delete('id2');
assert.lengthOf(storage.getTasks(), 1);
assert.equal(storage.getTasks());
assert.equal(storage.getTasks().get('id1'), {});
assert.equal(storage.getTasks().get('id2'), undefined);
});

describe('on import', () => {
it('should keep stored items across imports', () => {
delete require.cache[require.resolve('../src/storage')];
Expand Down

0 comments on commit 7d443b0

Please sign in to comment.