docs/docs/api/cron.mdx
import Type from '@site/docs/api/components/type';
:::info
Current state: Stable
:::
The Strapi Cron Service provides a way to add, remove, start, and stop cron jobs in a Strapi application.
The createCronService() function returns an object that provides methods to manage cron jobs.
cron.add(tasks)tasks: <Type>Object</Type>thisAdds one or more cron tasks to the service.
tasks object is the name of the task.tasks object can be either a function, or an object with two properties: task and options.task property is used as the task function, and its options property is used as the cron expression options.const { createCronService } = require('packages/core/strapi/lib/services/cron.js');
const cron = createCronService();
const task = () => {
console.log('Task executed!');
};
cron.add({
myTask: {
task,
options: '*/5 * * * *', // Executes every 5 minutes.
},
'*/1 * * * *': () => console.log('A minute has passed.'),
});
cron.remove(name)name: <Type>String</Type>thisRemoves a cron task from the service.
name parameter is the name of the task to remove.const { createCronService } = require('packages/core/strapi/lib/services/cron.js');
const cron = createCronService();
const task = () => {
console.log('Task executed!');
};
cron.add({
myTask: {
task,
options: '*/5 * * * *', // Executes every 5 minutes.
},
});
cron.remove('myTask');
cron.start()thisStarts the cron service.
const { createCronService } = require('packages/core/strapi/lib/services/cron.js');
const cron = createCronService();
const task = () => {
console.log('Task executed!');
};
cron.add({
myTask: {
task,
options: '*/5 * * * *', // Executes every 5 minutes.
},
});
cron.start();
cron.stop()thisStops the cron service.
const { createCronService } = require('packages/core/strapi/lib/services/cron.js');
const cron = createCronService();
const task = () => {
console.log('Task executed!');
};
cron.add({
myTask: {
task,
options: '*/5 * * * *', // Executes every 5 minutes.
},
});
// Start the scheduled cron jobs
cron.start();
// Stops the cron jobs
cron.stop();
cron.destroy()thisDestroys the cron service.
stop() method.const { createCronService } = require('packages/core/strapi/lib/services/cron.js');
const cron = createCronService();
const task = () => {
console.log('Task executed!');
};
cron.add({
myTask: {
task,
options: '*/5 * * * *', // Executes every 5 minutes.
},
});
// Start the scheduled cron jobs
cron.start();
// Stops the cron jobs and remove all scheduled tasks
cron.destroy();
cron.jobs<Type>Array</Type>
<Type>Object</Type>
job: <Type>Job</Type> - Job object by node-scheduleoptions: <Type>String</Type> - String representing the recurrence of the job ( like '_/5 _ * * *' )name: <Type>String</Type> - The name of the task associated to the jobAn array of the cron jobs added to the service.