paint-brush
[Nodejs] Execute script in Schedule (Cron Job)by@peterchang_82818
51,741 reads
51,741 reads

[Nodejs] Execute script in Schedule (Cron Job)

by August 21st, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

It is an example of running Node.js script, which is triggered in every certain period(day/hour/min). <code class="markup--code markup--p-code">crontab</code> in Linux is doing same job but it happens to me which can’t fulfill my purpose:
featured image - [Nodejs] Execute script in Schedule (Cron Job)
 HackerNoon profile picture

It is an example of running Node.js script, which is triggered in every certain period(day/hour/min). crontab in Linux is doing same job but it happens to me which can’t fulfill my purpose:

To use crontab to trigger Node.js script:

    1. We can provide the full path to node /usr/local/bin/node in your cron job like:

30 6 1 * * /usr/local/bin/node /home/steve/example/script.js

  • Or making a script with the command, and then adding that to cron:

    #!/usr/bin/env sh node /home/campaigns/reporting/UNIT_TESTS/testCron.js > /home/campaigns/reporting/UNIT_TESTS/cron.log

However, the problem of two above method is messing up the path in __*Node.js*__, all the command is in absolut path, but the Node.js script uses relative path to import/require other modules. It causes the error of file not found. So we need to execute the cron under the directory of Node.js script, which contains all the module which will be used.

There is the example git, which can help understand more.

Install

This is the lib is used to keep the cron-job alive, which triggers the node script at certain time.

$ npm install --save node-cron

Usage

Import node-cron and schedule a task:

Read more

var cron = require('node-cron'); cron.schedule('* * * * *', function(){  console.log('running a task every minute');});

Run Node.js script in cron

  • To run script : $ node script1.js
  • And script: $ npm run script -- PeterGood
  • child_help.js is a amazing Node.js script from mout, which helps to manage multiple linux command.

Start a Daemon, and run

$ node cronNodeScript

Exceute scritp every 1 min




//exceute every 1 mincron.schedule('*/1 * * * *', function(){....});

Exceute $ node script1.js and npm run script -- PeterGood every 1 min



//exceute every 1 mincron.schedule('*/1 * * * *', function(){var shell = require('./child_helper');

var commandList = \[  
    "node script1.js",  
    "npm run script -- PeterGood"  
\]

shell.series(commandList , function(err){  
//    console.log('executed many commands in a row');   
    console.log('done')  
});  

});

Reference: