Reputation: 2638
I have an express server as backend for my react app. Once a week each user should receive an email. I've looked up how cron jobs are done in Node and it seems to be quite straight forward. I would just set up a cron job that triggers the respective function, which loops through all the email addresses and sends out the mails. However, I'm not entirely sure if that's the way to go.
When sending emails, the server has to store the sent receipts. For that, it passes an email address to the respective API and awaits the receipt to store it in the DB. Therefore, sending an email might take a few minutes per user.
Now I'm wondering if setting up a cron job for this task will block my entire server until all emails are sent. Is it recommended to create a child process that is triggered by the cron job to loop through all the email adresses?
It would be great if you could give me some general recommendations and maybe examples, so that I know how to get started. Thank you for your time.
Upvotes: 3
Views: 2628
Reputation: 78
As suggested in this answer, it should not be blocking.
However, I think it is good practice not to use heavy cron jobs like this on your main server file. If you can, you should run a separate node.js app that will only deal with cron jobs.
Child processes should not be used for something you can easily deal with JS. You should keep them for specific tasks, such as DB backups for example.
var exec = require('child_process').exec;
var CronJob = require('cron').CronJob;
new CronJob('00 14 * * 4', function() {
sendNewsletter();
}, null, true);
new CronJob('00 12 * * *', function() {
exec('sh dbbackup.sh', function(err, stdout, stderr){
if (err) {
// handle error
}
});
}, null, true);
Upvotes: 3