CRON tasks outside of Strapi

Hello. I’m about to deploy to production and I’ve got two hurdles in my way. I will refer to the first one in this post and leave the second one for another post.

My application uses Strapi’s built-in CRON feature to deliver bulk email. But as stated in the documentation:

Please note that Strapi’s built in CRON feature will not work if you plan to use pm2 or node based clustering. You will need to execute these CRON tasks outside of Strapi.

The infrastructure provider of my choice makes use of pm2 to monitor services. My question is:

How do I execute Strapi services outside Strapi in a scheduled way? Should I develop a sort of webhook to run that process?

Some guidance should be very appreciated.

1 Like

Hello @mrwindmills

When we reference this, we strictly mean using PM2 clusters (in the CLI when starting the process you define this with an -i 4 or an -i max which determines the number of instances that are started). The reason we don’t recommend this is simply because at the time the cron is supposed to fire, you will effectively have all the instances fire the same crontask.

If your provider is not using the instances parameter and you only have 1 instance running, there should be no issue. But outside of that you could create a simple node-cron script that runs calls against the API via REST or something (maybe writing a custom route/controller to handle the logic the built in crontask would do).

This script could be ran from pretty much anywhere.

4 Likes

Got it!. Thank you so much for your quick response.

Hi @DMehaffy, does this mean I cannot use Cron tasks when my Strapi is deployed with Kubernetes? Would every pod be firing the same Cron task at the same time? I have been asked to set up automatic future publication. Thank you for your help.

Yes, if you do any clustering at all (vertical or horizontal) you cannot use our built in crontasks. Effectively you would need to create a custom controller that performs the logic you want and do a simple request (could be as simple as a standard GET request) to execute that controller.

Ideally you would want authentication on this and we do have a guide on our docs on how to implement an API token feature for the v3, whereas the v4 will have this natively built in.

The problem is that clustered Strapi instances are not aware of each other (stateless) so they are not “smart enough” to talk to each other to basically say “hey I’m node 5 and I’ll run the crontask, don’t worry about it!” and you would end up with all of your nodes firing the task at the same time.

There are ways to build the crontasks with some custom logic to make them aware (basically checking a custom entry in the database) but you start getting into deeply complex logic with that with very little benefit.

Thank you for the response!

Thank you @DMehaffy for your help. Here is the link to the workaround for version 3.
API token v3