Search code examples
javascriptnode.jsnode-cronnode-schedule

How to set schedule to run a certain file at a certain timing?


I want to try run this file on command prompt at 10am everyday, but this code does not seem to be working.

const schedule = require("node-schedule");
var dailyJob = schedule.scheduleJob("0 0 10 * *", function() {
   console.log("Its connecting to database....");
});
dailyJob.start();

Solution

  • You seem to misunderstand how the scheduler works. The scheduler will only work as long as your script is running. If you stop your script, the scheduler will not work. So if your script is not running at 10am, it will not execute your function.

    If you want a script to be executed without your script running you need register a cronjob in the system.

    For Linux, you create a script.js file, then call crontab -e to add a cronjob with this line:

    0 10 * * * node /path/to/script.js
    

    This will run your script every day at 10am. See this wiki on stackoverflow for more information.