diff --git a/packages/core/strapi/lib/services/cron.js b/packages/core/strapi/lib/services/cron.js index 4b1f6136cd..4df2f1bfd4 100644 --- a/packages/core/strapi/lib/services/cron.js +++ b/packages/core/strapi/lib/services/cron.js @@ -14,10 +14,15 @@ const createCronService = () => { let fn; let options; + let taskName; if (isFunction(taskValue)) { + // don't use task name if key is the rule + taskName = null; fn = taskValue.bind(tasks); options = taskExpression; } else if (isFunction(taskValue.task)) { + // set task name if key is not the rule + taskName = taskExpression; fn = taskValue.task.bind(taskValue); options = taskValue.options; } else { @@ -29,7 +34,7 @@ const createCronService = () => { const fnWithStrapi = (...args) => fn({ strapi }, ...args); const job = new Job(null, fnWithStrapi); - jobsSpecs.push({ job, options }); + jobsSpecs.push({ job, options, name: taskName }); if (running) { job.schedule(options); @@ -37,6 +42,13 @@ const createCronService = () => { } return this; }, + remove(name) { + if (!name) throw new Error('You must provide a name to remove a cron job.'); + const matchingJobsSpecs = jobsSpecs.filter(({ name: jobSpecName }) => jobSpecName === name); + matchingJobsSpecs.forEach(({ job }) => job.cancel()); + jobsSpecs = jobsSpecs.filter(({ name: jobSpecName }) => jobSpecName !== name); + return this; + }, start() { jobsSpecs.forEach(({ job, options }) => job.schedule(options)); running = true; @@ -52,6 +64,7 @@ const createCronService = () => { jobsSpecs = []; return this; }, + jobs: jobsSpecs, }; };