简体   繁体   English

是否建议使用Node.js中的cron作业的子进程?

[英]Are child processes for cron jobs in Node.js recommended?

I have an express server as backend for my react app. 我有一个Express服务器作为我的React应用程序的后端。 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. 我查看了Node中的cron作业是如何完成的,这似乎很简单。 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. 我只是设置一个cron作业来触发相应的功能,该功能遍历所有电子邮件地址并发送邮件。 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. 为此,它将电子邮件地址传递给相应的API,然后等待收据将其存储在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. 现在,我想知道是否为此任务设置cron作业会阻塞我的整个服务器,直到发送完所有电子邮件为止。 Is it recommended to create a child process that is triggered by the cron job to loop through all the email adresses? 是否建议创建一个由cron作业触发的子进程以遍历所有电子邮件地址?

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. 感谢您的时间。

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. 但是,我认为最好不要在主服务器文件上使用像这样的繁琐的cron作业。 If you can, you should run a separate node.js app that will only deal with cron jobs. 如果可以,您应该运行一个单独的node.js应用程序,该应用程序仅处理cron作业。

Child processes should not be used for something you can easily deal with JS. 子进程不应用于可以轻松处理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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM