Cron jobs
The content of this page has not been updated to Strapi v5 yet.
The cron.enabled
configuration option should be set to true
in the ./config/server.js
(or ./config/server.ts
for TypeScript projects) file.
cron
allows scheduling arbitrary functions for execution at specific dates, with optional recurrence rules. These functions are named cron jobs. cron
only uses a single timer at any given time, rather than reevaluating upcoming jobs every second/minute.
This feature is powered by the node-schedule
package.
The cron
format consists of:
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
To define cron jobs and have them run at the required times:
Optionally, cron jobs can be directly created in the cron.tasks
key of the server configuration file.
Creating a cron job
A cron job can be created using the object format or key format.
Using the object format
To define a cron job with the object format, create a file with the following structure:
- JavaScript
- TypeScript
module.exports = {
/**
* Simple example.
* Every monday at 1am.
*/
myJob: {
task: ({ strapi }) => {
// Add your own logic here (e.g. send a queue of email, create a database backup, etc.).
},
options: {
rule: "0 0 1 * * 1",
},
},
};
export default {
/**
* Simple example.
* Every monday at 1am.
*/
myJob: {
task: ({ strapi }) => {
// Add your own logic here (e.g. send a queue of email, create a database backup, etc.).
},
options: {
rule: "0 0 1 * * 1",
},
},
};
Advanced example #1: Timezones
Advanced example #2: One-off cron jobs
Advanced example #3: Start and end times
Using the key format
Using the key format creates an anonymous cron job which may cause issues when trying to disable the cron job or with some plugins. It is recommended to use the object format.
To define a cron job with the key format, create a file with the following structure:
- JavaScript
- TypeScript
module.exports = {
/**
* Simple example.
* Every monday at 1am.
*/
"0 0 1 * * 1": ({ strapi }) => {
// Add your own logic here (e.g. send a queue of email, create a database backup, etc.).
},
};
export default {
/**
* Simple example.
* Every monday at 1am.
*/
"0 0 1 * * 1": ({ strapi }) => {
// Add your own logic here (e.g. send a queue of email, create a database backup, etc.).
},
};
Enabling cron jobs
To enable cron jobs, set cron.enabled
to true
in the server configuration file and declare the jobs:
- JavaScript
- TypeScript
const cronTasks = require("./cron-tasks");
module.exports = ({ env }) => ({
host: env("HOST", "0.0.0.0"),
port: env.int("PORT", 1337),
cron: {
enabled: true,
tasks: cronTasks,
},
});
import cronTasks from "./cron-tasks";
export default ({ env }) => ({
host: env("HOST", "0.0.0.0"),
port: env.int("PORT", 1337),
cron: {
enabled: true,
tasks: cronTasks,
},
});