我想做一个可重复的工作,每15分钟发送一次邮件,从数据库表中获取数据。在节点js中,我可以创建作业,但是通过PM2,我不知道将代码放在哪里以及它是如何工作的。
发布于 2017-03-08 13:26:43
谢谢你的回答,我这样做,只需设置电子邮件。
1.
npm install node-crontabvar crontab = require('node-crontab');
var jobId = crontab.scheduleJob("*/15 * * * *", function(){
//This will call this function every 15 minutes
console.log("It's been 15 minutes!");
});发布于 2017-03-01 22:36:37
使用--cron选项:
-c --cron
<cron_pattern>
例如:
pm2 start sendMail.js --cron "*/15 * * * *"
Pm2现在将在每小时15、30和45分钟重新启动sendMail.js脚本。
发布于 2019-01-31 07:52:45
这就是我的工作原理,我将cron拆分到一个不同的文件中,这个文件运行在不同的进程中,因为我想在cron完成执行之后释放资源。
ecosystem.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
}
]
};以下几行在cron可执行文件中很重要
cron_restart: "0,30 * * * *" <- cron表达式
autorestart: false <-重要,因为否则pm2将在完成后立即重新启动cron
另外,确保您的instances为1,否则多个cron进程将运行。
主要注意事项:
无论何时执行pm2重新启动所有操作,cron作业都将运行,而不管cron表达式如何。如果只在特定时间运行至关重要,请在cron文件的开头添加此附加检查。
if (new Date().getHours() !== 0 ) {
console.log(`Current hours is ${new Date().getHours()}, not running.`)
process.exit(0);
}https://stackoverflow.com/questions/42501219
复制相似问题