Schedule Cron tasks for Strapi

According to Wikipedia:

The software utility cron also known as cron job is a time-based job scheduler in Unix-like computer operating systems. Users who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like downloading files from the Internet and downloading email at regular intervals.

CRON tasks allow you to schedule jobs (arbitrary functions) for execution at specific dates, with optional recurrence rules. It only uses a single timer at any given time (rather than reevaluating upcoming jobs every second/minute).

This feature is powered by node-schedule node modules.

To write cron jobs in Strapi is super simple! In this tutorial I will show you how you can enable and write cron jobs for Strapi.

Understand the Cron Task Format #

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)

You can use the symbols to specify more details:

This list contains valid symbols with explaination:

*    any value
,    value list separator
-    range of values
/    step values

Example:

This cron string:

5  0  *  8  *

means: “At 00:05 in August.”

Enable Cron Tasks for Strapi #

To write cron tasks in Strapi, we first need to enable them. To do so, we have to edit the config/server.js

// config/server.js

cron: { enabled: true }

A complete example might look like this.

// config/server.js

module.exports = ({ env }) => ({
  host: env('HOST', '0.0.0.0'),
  port: env.int('PORT', 1337),
  admin: {
    auth: {
      secret: env('ADMIN_JWT_SECRET', 'VerySecretString'),
    },
  },
  cron: { enabled: true },
});

Write Cron Tasks for Strapi #

To write cron tasks for strapi, we have to edit config/functions/cron.js file.

You can create as many cron tasks as you want, all you need to do is add the cron string as a key and the handler function as value to the exported objects. Let see an example of scheduling posts

// config/functions/cron.js

'use strict';

/**
 * Cron config that gives you an opportunity
 * to run scheduled jobs.
 *
 * The cron format consists of:
 * [SECOND (optional)] [MINUTE] [HOUR] [DAY OF MONTH] [MONTH OF YEAR] [DAY OF WEEK]
 *
 * See more details here: https://strapi.io/documentation/v3.x/concepts/configurations.html#cron-tasks
 */

module.exports = {
 '*/5 * * * *': async () => {
    const markdownPosts = await strapi.api.post.services.post.find({
      _publicationState: 'preview',
      published_at_lt: new Date()
    });

    // update publish_at of articles
    markdownPosts.forEach(async article => {
      await strapi.api.post.services.post.update(
        { id: article.id },
        { published_at: new Date() }
      );
    });
};

I hope this tutorial can help you get started and use Strapi's cron job, and hope to automate some repetitive tasks.

Tags:

Javascript