3

I would like to use node-schedule to run a certain node script at a certain time. Can I do something like this in node.js?

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

//https://www.npmjs.com/package/node-schedule
var j = schedule.scheduleJob('00 00 22 * * *', function () {
    console.log('Running XX node.js script ...');

    NodeShell.run(__dirname + '\\XX.js', function (err) {
        if (err) throw err;
        console.log('finished');
    });
});

Not sure if something like NodeShell exists. Other alternatives would be welcomed.

guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • 1
    There are a [bunch](https://nodejs.org/api/child_process.html#child_process_asynchronous_process_creation) of ways to spawn processes in node.js. – go-oleg May 21 '16 at 01:13
  • If you dont want to create new processes using `child_process` module, `vm` is the way to go: http://stackoverflow.com/a/8808328/405398 –  May 21 '16 at 05:17
  • why not just simply use require. running node script doesnot make sense however some bash or other script looks ok !!! – owais Aug 31 '16 at 01:33
  • Why cant you just do this with a cronjob ? – Vibhaj Sep 04 '16 at 16:12

1 Answers1

8

You have several options, all of which are listed in the docs for child_process. Briefly:

  • child_process.exec spawns a shell
  • child_process.fork forks a node process
  • child_process.spawn spawns a process

For your case, to run a node script you could use something like this:

var childProcess = require("child_process");
var path = require("path");
var cp = childProcess.fork(path.join(__dirname, "xx.js"));
cp.on("exit", function (code, signal) {
    console.log("Exited", {code: code, signal: signal});
});
cp.on("error", console.error.bind(console));
ZachB
  • 13,051
  • 4
  • 61
  • 89