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.

4
  • 1
    There are a bunch of ways to spawn processes in node.js. Commented May 21, 2016 at 1:13
  • If you dont want to create new processes using child_process module, vm is the way to go: stackoverflow.com/a/8808328/405398 Commented May 21, 2016 at 5:17
  • why not just simply use require. running node script doesnot make sense however some bash or other script looks ok !!! Commented Aug 31, 2016 at 1:33
  • Why cant you just do this with a cronjob ? Commented Sep 4, 2016 at 16:12

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.