JavaScript
min read
Last update on

Mastering Cron Jobs in CMS: a practical guide with Strapi

Mastering Cron Jobs in CMS: a practical guide with Strapi
Table of contents

In modern web development, automation plays a crucial role in enhancing productivity and ensuring applications run smoothly. One common and effective tool for automation is the cron job, which allows developers to schedule specific tasks to run at set intervals. 

For content-driven applications, automation can simplify workflows such as publishing articles, clearing outdated entries, or syncing external data. Strapi, a popular headless CMS built with Node.js, supports cron jobs natively using straightforward JavaScript syntax, making it easier to set up recurring tasks, like scheduling blog posts to go live at a certain time or cleaning up draft content every night.

What is a Cron Job?

A cron job is a time-based task scheduler commonly used in Unix-like operating systems. It allows you to automate the execution of scripts or commands at specific times or intervals, such as every minute, hour, or day. 

You can think of it as setting an alarm clock for your server, helping it perform routine tasks like sending email reports, clearing logs, or updating content without manual effort.

Example Cron schedule syntax

Cron schedule syntax

How to set up Cron jobs in Strapi

To configure and run cron jobs in Strapi:

  1. Create the necessary cron job file.
  2. Enable cron jobs in your server.js configuration file.

💡 Tip: Optionally, cron jobs can be directly created in the cron.tasks key of the server configuration file.

Creating a Cron job in Strapi

Strapi supports defining cron jobs using two formats:

1. Object format (recommended) 

To define a cron job using the object format:

1. Create or edit the file at:

./config/cron-tasks.js   // For Strapi v5


2. Use the following structure inside that file:

./config/cron-tasks.js 
module.exports = {
  /**
   * Simple example.
   * Every Monday at 1am.
   */

  myJob: {
    task: async({ strapi }) => {
      // Add your own logic here (e.g. send a queue of email, create a database backup, etc.).
    },
    options: {
      rule: "0 0 1 * * 1",
    },
  },
};

In this format:

  • The rule ('0 0 1 * 1') is a standard cron expression that defines when the task runs.
  • The value is an async function that contains the code to be executed.

The following cron job runs on a specific timezone:

./config/cron-tasks.js 
module.exports = {

  /**
   * Cron job scheduled with timezone support.
   * This task runs every Monday at 1:00 AM (Asia/Dhaka timezone).
   * Reference for valid timezones: 
   * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List
   */

  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',
      tz: 'Asia/Dhaka',    // Timezone in which the job should execute
    },
  },
};

The following cron job is run only once at a given time:

./config/cron-tasks.js 
module.exports = {
  myJob: {
    task: ({ strapi }) => {
      /* Add your own logic here */
    },
    // only run once after 10 seconds
    options: new Date(Date.now() + 10000),
  },
};

The following cron job uses start and end times:

./config/cron-tasks.js 
module.exports = {
  myJob: {
    task: ({ strapi }) => {
      /* Add your own logic here */
    },
    options: {
      rule: "* * * * * *", // Runs Every second
      // start 10 seconds from now
      start: new Date(Date.now() + 10000),
      // end 20 seconds from now
      end: new Date(Date.now() + 20000),
    },
  },
};

2. Key format 

To define a cron job using the key format:

1. Create or edit the file at:

./config/cron-tasks.js   // For Strapi v5


2. Use the following structure inside that file:

./config/cron-tasks.js 
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.).
  },
};

In this format, the cron rule is used directly as the key instead of naming the job explicitly, resulting in the creation of an anonymous cron job.

Warning:

Using the key format to define cron jobs results in anonymous jobs, which may cause problems when attempting to disable them or when working with certain plugins. For improved control and compatibility, it's always advisable to use the object format instead.

Enabling Cron jobs

To enable cron jobs in Strapi, set cron.enabled to true in the server configuration file and register your defined tasks as shown below:

// ./config/server.js
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,
  },
});

This setup ensures that Strapi will run the scheduled tasks defined in your /config/cron-tasks.js file.

Adding, removing, and listing Cron jobs in Strapi

You can dynamically manage cron jobs in Strapi using the built-in strapi.cron methods:

1. Adding Cron jobs

To programmatically add a cron job, use strapi.cron.add() within your plugin or custom code:

// ./src/plugins/my-plugin/strapi-server.js
module.exports = () => ({
  bootstrap({ strapi }) {
    strapi.cron.add({
      myJob: {
        // This job runs every second
        task: ({ strapi }) => {
          console.log("Hello from plugin");
        },
        options: {
          rule: "* * * * * *",
        },
      },
    });
  },
});

2. Removing Cron jobs

To remove a cron job by its name, use strapi.cron.remove() and provide the key:

strapi.cron.remove("myJob");

Note: Cron jobs defined using the key format (i.e., where the rule itself is the key) cannot be removed.

3. Listing Cron jobs

To get a list of all active(currently running) cron jobs anywhere in your custom code, use:

strapi.cron.jobs

This will return the current cron jobs registered in the application.

Example: auto- publish scheduled blog posts in Strapi

A case where you want to allow your content editors to schedule blog posts to go live at a specific time in the future. Here's how we can achieve that with a cron job in Strapi.

Setup: Content type

Let's assume your BlogPost content type has these fields:

  • title (Text)
  • content (Rich Text)
  • publishAt (Datetime) — custom field for scheduling
  • publishedAt (Datetime) — default field handled by Strapi

Step-by-step implementation

1. Enable Cron Jobs in config/server.js

module.exports = ({ env }) => ({
  cron: {
    enabled: true,
  },
});

2. Add Cron Job in /config/cron-tasks.js

module.exports = {
  autoPublishBlogPosts: {
    task: async ({ strapi }) => {
      const now = new Date().toISOString();

      const posts = await strapi.entityService.findMany('api::blog-post.blog-post', {
        filters: {
          publishAt: { $lte: now },
          publishedAt: null, // Only unpublished posts
        },
      });

      for (const post of posts) {
        await strapi.entityService.update('api::blog-post.blog-post', post.id, {
          data: {
            publishedAt: new Date().toISOString(),
          },
        });

        strapi.log.info(`Auto-published post: "${post.title}"`);
      }
    },
    options: {
      rule: '*/1 * * * *', // Runs every minute
     },
  },
};

Testing the Cron job

  1. Add a blog post in the Strapi admin collection(api::blog-post.blog-post) and save it without publishing.
  2. Set publishAt to a future time.
  3. Leave publishedAt empty.
  4. Wait until the scheduled time passes.
  5. Strapi will automatically update publishedAt, marking it as live.

Real-world use cases of Cron jobs

  • Automated Report Generation
  • Cleaning up old data or logs
  • Sending scheduled emails or notifications
  • Backing up databases at night
  • Auto-publishing or unpublishing CMS content

Conclusion 

Cron jobs are essential in modern development. Paired with CMS platforms like Strapi, they handle content publishing, data syncing, and background tasks without extra tools.

Now AI is making them smarter.

Platforms like Cronly use real-time data like server load and user activity to schedule tasks at the best possible moment. They also detect errors and fix issues before they cause problems.

Strapi is used by over 2,000 companies in more than 50 countries. Teams across e-commerce, media, and tech rely on cron jobs to keep content fresh and systems running smoothly.

AI takes this further. It enables predictive publishing, real-time triggers, and personalised content delivery. According to PostWhale, CMS platforms are moving toward fully automated, AI-powered workflows.

Cron jobs aren’t outdated. They’re evolving into smart automation tools that make digital operations faster, lighter, and more reliable.

Written by
Editor
Ananya Rakhecha
Tech Advocate