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 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,
};
};