node.js 如何使用 PM2 进行 cron 作业

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42501219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:02:55  来源:igfitidea点击:

How to make a cron job with PM2

node.jspm2

提问by Milan Mahata

I want to make a cron job to send mail every 15 minutes taking data from a database table. In node js I can make a cron job but through PM2 I don't understand where to place the code and how it works.

我想做一个 cron 作业,每 15 分钟从数据库表中获取数据发送一次邮件。在 node js 中,我可以进行 cron 作业,但通过 PM2,我不知道将代码放在哪里以及它是如何工作的。

采纳答案by Milan Mahata

thank you for your answer; i do it in this way and just set the email

谢谢您的回答; 我是这样做的,只是设置了电子邮件

  1. npm install node-crontab
  1. npm install node-crontab

2. var crontab = require('node-crontab');

2. var crontab = require('node-crontab');

var jobId = crontab.scheduleJob("*/15 * * * *", function(){

var jobId = crontab.scheduleJob("*/15 * * * *", function(){

//This will call this function every 15 minutes

console.log("It's been 15 minutes!");

});

});

回答by Robbie

Use the --cronoption:

使用--cron选项:

-c --cron <cron_pattern>

-c --cron <cron_pattern>

For example:

例如:

pm2 start sendMail.js --cron "*/15 * * * *"

pm2 start sendMail.js --cron "*/15 * * * *"

Pm2 will now restart the sendMail.jsscript on the hour, and at 15, 30 and 45 minutes past the hour

Pm2 现在将sendMail.js在整点和整点后的15、30和 45 分钟重新启动脚本

回答by Sanket Berde

This is what worked for me, I split the cron in a different file which runs in a different process because i want to free up resources after cron has completed execution.

这对我有用,我将 cron 拆分到在不同进程中运行的不同文件中,因为我想在 cron 完成执行后释放资源。

ecosystem.config.js:

生态系统.config.js:

module.exports = {
  /**
   * Application configuration section
   * http://pm2.keymetrics.io/docs/usage/application-declaration/
   */
  apps: [

    // Main API Hosting
    {
      name: 'API',
      script: 'bin/www',
      env: {
        COMMON_VARIABLE: 'true'
      },
      instances: 1,
      exec_mode: 'cluster',
      watch: false,
      autorestart: true
    },
    {
      name: 'CRON',
      script: "crons/cronjob.js",
      instances: 1,
      exec_mode: 'fork',
      cron_restart: "0,30 * * * *",
      watch: false,
      autorestart: false
    }
  ]
};

The following lines are important in the cron executable

以下几行在 cron 可执行文件中很重要

cron_restart: "0,30 * * * *"<- cron expression

cron_restart: "0,30 * * * *"<- cron 表达式

autorestart: false<- important because otherwise pm2 will restart the cron after completion immediately

autorestart: false<- 重要,否则 pm2 将在完成后立即重新启动 cron

Also make sure your instancesis 1 otherwise multiple cron processes will run.

还要确保您的instances值为 1,否则将运行多个 cron 进程。

Key caveats:

关键警告:

Whenever you do pm2 restart all, the cron job will run irrespective of the cron expression. If Its critical to run only at specific times, add this additional check in the beginning of the cron file

每当您执行 pm2 restart all 时,无论 cron 表达式如何,cron 作业都会运行。如果仅在特定时间运行很重要,请在 cron 文件的开头添加此附加检查

if (new Date().getHours() !== 0 ) {
  console.log(`Current hours is ${new Date().getHours()}, not running.`)
  process.exit(0);
}

回答by Adam Bubela

If you use PM2 ecosystemthen in the config file add cron sequence to scriptparam by wrapping it with single quotes. Somehow double quotes didn't work for me.

如果您使用 PM2生态系统,则在配置文件中将 cron 序列添加到scriptparam 中,方法是用单引号包裹它。不知何故,双引号对我不起作用。

module.exports = {
  apps : [{
    name        : "Send-mail",
    script      : "./sendMail.js --cron '*/15 * * * *'",
    watch       : true
  }]
}

alternatively (my preference)

或者(我的偏好)

module.exports = {
  apps : [{
    name        : "Send-mail",
    script      : "./sendMail.js",
    cron_restart: "*/15 * * * *",
    watch       : true
  }]
}

回答by Dan Watts

You can also use the node-schedule module which allows you to define cron style rules. Then, you can run the program normally in pm2, I use this with PM2 for a lot of projects and it has never let me down.

您还可以使用 node-schedule 模块,它允许您定义 cron 样式规则。然后,你可以在pm2中正常运行程序,我在PM2中使用了很多项目,它从未让我失望。

var schedule = require('node-schedule');

var rule = new schedule.RecurrenceRule();
rule.hour = [10]; // 10am
rule.minute = [0]; // 0mins

var job = schedule.scheduleJob(rule, function(){
    console.log("10am every day")
});         

//Rule 2 - 6am every wednesday
var rule2 = new schedule.RecurrenceRule();
rule2.dayOfWeek = 3; // 0 = Sunday
rule2.hour = 6;
rule2.minute = 0;

var job2 = schedule.scheduleJob(rule2, function(){
    console.log("Every Wednesday @ 6am");
});


var rule3 = new schedule.RecurrenceRule();
rule3.minute = [0, 15, 30, 45]; // Specific Minutes

var job3 = schedule.scheduleJob(rule3, function(){
    console.log("Run at specific minutes")
});         

It also supports CRON style rules, but I prefer the above method.

它还支持 CRON 样式规则,但我更喜欢上面的方法。

Check out the documentation at https://www.npmjs.com/package/node-schedule

https://www.npmjs.com/package/node-schedule查看文档