Hi I was wondering If anyone got examples of using Cron Schedule functions on Strapi: https://strapi.io/documentation/3.x.x/configurations/configurations.html#functions like sending email, accessing the strapi config, etc.
'*/1 * * * *': async() => {
console.log("I am running " + new Date(), Object.keys(strapi.config));
await strapi.services.article.publish();
}
In your-project/config/functions/cron.js. you can add as many functions in the above format. The function name in itself is a cron expression which is parsed by strapi to execute at frequent intervals. There are many online tools that will tell you the cron expression that you want to create.
The above function runs every 1 minute, by which I am publishing a content type by using strapi.services. i.e. in file your-project/api/article/services/Article.js I have written a service layer method that at the moment is publishing an article.
Similarly, you can send an email from your email content type or any utility file that you have made to trigger an email. For accessing strapi config use: strapi.config object instead of strapi.services
Some example of CRON jobs for Strapi
add this line server.js
...
port: env.int('PORT', 1337),
cron :{
enabled: true
},
admin:
...
cron.js some examples
module.exports = {
/**
* Simple examples.
*/
'*/5 * * * * *': () => {
console.log("🚀 ~ file: cron.js ~ executing action ~Every 5sec");
},
'*/10 * * * * *': () => {
console.log("🚀 ~ file: cron.js ~ executing action ~Every 10sec");
},
'* */5 * * * *': () => {
console.log("🚀 ~ file: cron.js ~ executing action ~Every 5min");
},
'* * */5 * * *': () => {
console.log("🚀 ~ file: cron.js ~ executing action ~Every 5hour");
},
};
Strapi 3 has cron jobs turned off by default. Make sure you turn them on first :)
You also don't need to do */1 for every minute in a cron job, just *, as * means every, and it only checks once a minute.
My requirement was to fetch data from an external MSSQL DB (master data) hosted under RDS (AWS) and update the strapi product catolog (mongodb) every minute.
I've created a custom "cron" folder under "root" to keep all my custom modules in order keep a clean "cron.js".
Under "cron.js" i've simply imported my custom module to call the external module:
const fwSync = require('../../cron/dataSync');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With