0

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();
Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105
Koh Shuan Jin
  • 551
  • 1
  • 5
  • 8

2 Answers2

4

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!

Md. Abu Taher
  • 17,395
  • 5
  • 49
  • 73
  • yes, it does.. but however, how how do i let the program type in "node testing.js" by itself in the command prompt. It is requested by my teacher that the program will run by itself whenever the time is up. – Koh Shuan Jin Apr 04 '19 at 08:42
  • Something still has to run and wait for the time, right? All my answer above was for nodeJS and not for the operating system. There are several ways to resolve this however I need to know which OS you use and a bit more details about your problem. – Md. Abu Taher Apr 04 '19 at 12:49
0

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.

Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105