如何使用服务器上的调度程序自动运行我的节点 js 脚本 [英] How can I run my node js script automatically using scheduler on server

查看:63
本文介绍了如何使用服务器上的调度程序自动运行我的节点 js 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a nodejs file using express enviornment and running the file on server using nodemon. Currently I have to give commands to the interface to run the particular file on nodemon but what I currently need is to schedule the task to run that file on server automatically at multiple occasion in a single day.

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

my file excute like this on terminal::

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 终端上运行 node js,但我的文件将在具有 linux 界面的服务器上运行

推荐答案

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

使用 node-schedulenode-cron 包以在所需的时间或间隔运行您的代码块.

Use node-schedule or node-cron packages to run your code block at desired time or interval.

i.node-schedule

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

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

ii.node-cron

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

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

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

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

You can use Linux crontab to execute your script at desired time

crontab -e

并添加以下条目

*/30 * * * * /usr/local/bin/node /home/ridham/example/script.js

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

This will execute /home/ridham/example/script.js every 30 minutes. and always give full qualified path here.

您必须在以下任何一项中提供 crontime.您可以在此处

You have to give crontime in any of the following. you can learn about crontime here

这篇关于如何使用服务器上的调度程序自动运行我的节点 js 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆