Koh Shuan Jin
Koh Shuan Jin

Reputation: 651

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();

Upvotes: 0

Views: 1324

Answers (2)

Thomas Dondorf
Thomas Dondorf

Reputation: 25280

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.

Upvotes: 0

Md. Abu Taher
Md. Abu Taher

Reputation: 18876

You have to have the script running in the background or make it as a service.

Step 1: Make a schedule script

There are many packages for scheduling, most are cron based.

This is a sample with cron package,

var CronJob = require('cron').CronJob;
new CronJob('* * * * * *', function() {
  console.log('You will see this message every second', Date.now());
}, null, true, 'America/Los_Angeles');

When you run this, does it log a new line every second?

enter image description here

Great!

Step 2: Make it run on background

So how can you run it on background or as a service? There are lots of options here too, forever, pm2, systemctl etc. I'll use pm2.

Go over and install pm2,

npm i -g pm2

Start the script you want to run on background,

pm2 start index.js --name=run-every-second

Check the logs,

pm2 logs run-every-second

And it will continue to run on background,

enter image description here

You can even make it run on startup and so on using,

pm2 startup
pm2 save

Peace!

Upvotes: 4

Related Questions