如何在服务器上使用调度程序自动运行Node js脚本

kri*_*thi 3 linux scheduler scheduled-tasks node.js server

我已经使用express环境创建了一个nodejs文件,并使用nodemon在服务器上运行该文件。当前,我必须向界面提供命令以在nodemon上运行特定文件,但是我目前需要的是安排任务,以便在一天之内多次在服务器上自动运行该文件。

我的文件在终端上这样执行::

nodemon example_api.js
Run Code Online (Sandbox Code Playgroud)

输出端子:

    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
Run Code Online (Sandbox Code Playgroud)

注意:我目前正在使用Windows在Mobaxterm终端上运行node js,但我的文件将在具有linux接口的服务器上运行

Rid*_*ara 6

1.如果要连续运行节点进程,并且只想运行特定任务:

使用node-schedulenode-cron程序包在所需的时间或间隔运行代码块。

节点计划

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

var j = schedule.scheduleJob('*/30 * * * * ', function(){
  console.log('The answer to life, the universe, and everything!');
});
Run Code Online (Sandbox Code Playgroud)

ii。节点克隆

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

cron.schedule('*/30 * * * *', function(){
  console.log('The answer to life, the universe, and everything!');
});
Run Code Online (Sandbox Code Playgroud)

2.如果只想运行单节点脚本:

您可以在需要的时间使用Linux crontab执行脚本

crontab -e
Run Code Online (Sandbox Code Playgroud)

并添加以下条目

*/30 * * * * /usr/local/bin/node /home/ridham/example/script.js
Run Code Online (Sandbox Code Playgroud)

这将/home/ridham/example/script.js每30分钟执行一次。并始终在此处给出完整的合格路径。

您必须使用以下任意一种方式设置crontime。您可以在这里了解crontime