Merge pull request #15587 from cpaczek/add-cron-removals

This commit is contained in:
Ben Irvin 2023-03-07 15:46:22 +01:00 committed by GitHub
commit 5c9b3896c8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -14,10 +14,15 @@ const createCronService = () => {
let fn; let fn;
let options; let options;
let taskName;
if (isFunction(taskValue)) { if (isFunction(taskValue)) {
// don't use task name if key is the rule
taskName = null;
fn = taskValue.bind(tasks); fn = taskValue.bind(tasks);
options = taskExpression; options = taskExpression;
} else if (isFunction(taskValue.task)) { } else if (isFunction(taskValue.task)) {
// set task name if key is not the rule
taskName = taskExpression;
fn = taskValue.task.bind(taskValue); fn = taskValue.task.bind(taskValue);
options = taskValue.options; options = taskValue.options;
} else { } else {
@ -29,7 +34,7 @@ const createCronService = () => {
const fnWithStrapi = (...args) => fn({ strapi }, ...args); const fnWithStrapi = (...args) => fn({ strapi }, ...args);
const job = new Job(null, fnWithStrapi); const job = new Job(null, fnWithStrapi);
jobsSpecs.push({ job, options }); jobsSpecs.push({ job, options, name: taskName });
if (running) { if (running) {
job.schedule(options); job.schedule(options);
@ -37,6 +42,13 @@ const createCronService = () => {
} }
return this; 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() { start() {
jobsSpecs.forEach(({ job, options }) => job.schedule(options)); jobsSpecs.forEach(({ job, options }) => job.schedule(options));
running = true; running = true;
@ -52,6 +64,7 @@ const createCronService = () => {
jobsSpecs = []; jobsSpecs = [];
return this; return this;
}, },
jobs: jobsSpecs,
}; };
}; };