我使用express enviornment创建了一个nodejs文件,并使用nodemon在服务器上运行该文件。目前,我必须向接口发出命令以在nodemon上运行特定文件,但我目前需要的是安排任务在一天内多次自动在服务器上运行该文件。
我的文件在终端上执行如下::
nodemon example_api.js
输出终端:
root@*********:/var/www/example project# nodemon example_api.js
[nodemon] ##.##.#####
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node api.js`
Listening on port 8080
注意:我目前正在使用Windows的Mobaxterm终端上运行节点js但我的文件将在具有linux接口的服务器上运行
1.如果要连续运行节点进程并且只想运行特定任务:
使用node-schedule或node-cron包在所需的时间或间隔运行代码块。
i.node时间表
var schedule = require('node-schedule');
var j = schedule.scheduleJob('*/30 * * * * ', function(){
console.log('The answer to life, the universe, and everything!');
});
好。没有c
var cron = require('node-cron');
cron.schedule('*/30 * * * *', function(){
console.log('The answer to life, the universe, and everything!');
});
2.如果只想运行单节点脚本:
您可以使用Linux crontab在所需的时间执行脚本
crontab -e
并添加以下条目
*/30 * * * * /usr/local/bin/node /home/ridham/example/script.js
这将每30分钟执行一次/home/ridham/example/script.js
。并始终在这里提供完全合格的路径。
您必须在以下任何一项中提供crontime。你可以了解crontime here
对于一个简单的实现 - 你可以像这样使用setInterval
:
setInterval(() => {
// do something every 5 seconds
}, 5000);
但是你想要像cron这样的东西,那么,你可能想和node-cron或node-schedule一起去。
您还可以使用AWS CloudWatch等提供商。 AWS CloudWatch允许您在cron上运行AWS Lambda函数。