Running a Node.js script between certain hours everyday

Viewed 357

I am trying to run a Javascript file everyday specifically between 9 am and 5 pm and I was wondering if there is a proper way to do it using cron or some other method. At 5 pm, I would like the running script to be ended as if I hit ctrl-c in the terminal. The following morning, it would automatically restart.

2 Answers

This can be done by dividing the task into two steps

  1. A cron job is to be scheduled that starts the node procces everyday at 9AM. For that suppose you have a node file named script.js and it's location is /home/user/example/script.js then the following command will be used to run it everyday at 9AM daily
* 9 * * * /usr/local/bin/node /home/user/example/script.js
  1. Now to close the script everyday a 5PM, this can be done implicitly using setTimeout function.Below is the code to be written in script.js
setTimeout((function() {
return process.exit(1);}), 28,8000,000);//28,8000,000 Milliseconds

This way the script.js will start it's execution daily at 9AM and stop at 5PM.

An option is to create a systemd service file for your script like this then you can use cron to start and stop the service at the required times.

Related