Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow removing tasks from current schedule #359

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 18 additions & 1 deletion src/node-cron.js
Expand Up @@ -29,6 +29,22 @@ function schedule(expression, func, options) {
return task;
}

/**
* Removes the passed task from current schedule
*
* @param {ScheduledTask} task The scheduled task to be removed.
* @returns {boolean} Whether the operation was successful or not.
*/
function removeTask(task) {
try {
storage.remove(task);

return true;
} catch (_) {
return false;
}
}

function createTask(expression, func, options) {
if (typeof func === 'string')
return new BackgroundScheduledTask(expression, func, options);
Expand Down Expand Up @@ -61,4 +77,5 @@ function getTasks() {
return storage.getTasks();
}

module.exports = { schedule, validate, getTasks };

module.exports = { schedule, validate, getTasks, removeTask };
8 changes: 8 additions & 0 deletions src/storage.js
Expand Up @@ -14,6 +14,14 @@ module.exports = (() => {
},
getTasks: () => {
return global.scheduledTasks;
},
remove: (task) => {
if(!task.options){
const uuid = require('uuid');
task.options = {};
task.options.name = uuid.v4();
}
global.scheduledTasks.delete(task.options.name, task);
}
};
})();
12 changes: 11 additions & 1 deletion test/node-cron-test.js
Expand Up @@ -12,6 +12,16 @@ describe('node-cron', () => {
});

describe('schedule', () => {
it('should schedule a task and then remove it', () => {
let task = cron.schedule('* * * * * *', './test/assets/dummy-task.js');
assert.isNotNull(task);
assert.isDefined(task);
assert.isTrue(task.isRunning());
assert.equal(1, cron.getTasks().size);
cron.removeTask(task);
assert.equal(0, cron.getTasks().size);
});

it('should schedule a task', () => {
let executed = 0;
cron.schedule('* * * * * *', () => {
Expand Down Expand Up @@ -70,7 +80,7 @@ describe('node-cron', () => {
assert.equal(0, executed);
});

it('should start a stoped task', () => {
it('should start a stopped task', () => {
let executed = 0;
let scheduledTask = cron.schedule('* * * * * *', () => {
executed += 1;
Expand Down