Strapi cron jobs just for production environment?

Hi Strapi Enthusiasts, I have an urgent configuration problem:

I need to setup a cron job that only runs in “production” environment. Is that possible?
I was able to run the cron job in ALL environments. But as soon as I move the cron script to config/env/production/functions/cron.js it is not being executed at all.
What am I doing wrong?

Thanks in advance!

Two things to keep in mind (one to only run in production)

  • Crons are executed based on the server’s timezone which should almost always be exclusively UTC, meaning your cron timing should be based on the fact it’s running in UTC (there is an open PR to address running them in a specific timezone here:

  • You can specify in the cron using an if() {} statement to check the current NODE_ENV as we do not have specific cron files for each environment.

Please do note that if you plan to use any clustering at all not just PM2 instance clustering, but also any higher level load balancing such as Nginx as a proxy for a cluster of Strapi backend servers, you should not use the built in Strapi cron function. This would lead to multiple servers running the same action at the same time and thus cause a race condition that could cause corruption/errors/unexpected results.

In place of something like that, I would recommend you build a custom route/controller to run the code and setup an external cron script, maybe using something like node-cron running either in PM2 itself, or even something serverless like an AWS lambda function.

First of all: Amazing support! :sunglasses:

Timezone is ok for me. If fixed it already using the one cron.js file and only execute it in specific NODE_ENV environments. That’s ok. Having different config/env/** folders for everything would be cleaner in my opinion.

And this should be added to the docs. Since cron.js lives inside /config folder the following statement in the docs is confusing:

When starting Strapi with NODE_ENV=production it will load the configuration from ./config/* and ./config/env/production/*. Everything defined in the production config will override the default config.

Especially the Everything defined in the production config part.

Thanks again and keep up the great work!

@alexandrebodin feature request to add in cron files for different environments? It would be a breaking change, but I think it would be a good one for v4

(maybe also the same for bootstrap too)

1 Like

I may be joining the party way too late but…

config files are being merged, right? Cron tasks don’t seem like the type of thing you’d like to get merged per environment. Maybe just update the docs to make it clearer the proper approach for environment-based cron tasks?

1 Like