Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run my node js script automatically using scheduler on server

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

output terminal:

    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

Note: I am currently running node js on Mobaxterm terminal currently using windows but my file will be run on a server with linux interface

like image 675
krishank Tripathi Avatar asked Feb 20 '18 12:02

krishank Tripathi


People also ask

How do I run a scheduler in Node JS?

Scheduling a Simple Task with node-cron Input the following code into the index. js file to create our simple task scheduler: const cron = require("node-cron"); const express = require("express"); const app = express(); cron. schedule("*/15 * * * * *", function () { console.

How do I keep node running on server?

js application locally after closing the terminal or Application, to run the nodeJS application permanently. We use NPM modules such as forever or PM2 to ensure that a given script runs continuously. NPM is a Default Package manager for Node.

What is the technique used to schedule jobs to specific nodes?

node-cron syntax It is a package used to schedule tasks (functions or commands) in Node. js. Its name is derived from the Greek word 'Chronos' meaning time. These tasks can be scheduled to either run once or repeatedly.


1 Answers

1. If you want to run your node process continuously and want to run only particular task:

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. If you want to run only single node script:

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

crontab -e

and add following entry

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

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

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

like image 85
Ridham Tarpara Avatar answered Nov 08 '22 18:11

Ridham Tarpara