Configure Cron Jobs in Linux

Problem: I need a Node.JS script to run automatically at a given time interval.

Solution: Configure a cron job to automatically run my script at the configured time interval.

Example: Let's say that I need to run a Node.JS script every 8 hours on my computer. Note that I am doing a lot of assumptions about the Node.JS installation and other things, your mileage may vary.

Method 1 (/etc/cron.d)

  1. Create a folder for logs
mkdir /var/log/my-logs
  1. Create a bash file
touch /usr/local/bin/my-bash-file.sh
  1. Make it executable
chmod 700 /usr/local/bin/my-bash-file.sh
  1. Open the file and paste the following line, then save and exit.
/usr/local/lib/nodejs/my-current-node-version/bin/node /usr/local/bin/my-nodejs-file.js > /var/log/my-logs/run-script.$(date +%Y-%m-%d_%H-%M-%S).log
  1. Create a file inside /etc/cron.d
touch /etc/cron.d/my-cron-file
  1. Open the file and paste the following line, then save and exit
0 */8 * * * root bash /usr/local/bin/my-bash-file.sh

This basically means that the command bash /usr/local/bin/my-bash-file.sh will be executed by user root at an interval of 0 */8 * * * (8 hours). Since my-bash-file.sh contains the command to run the Node.JS file the problem is be solved.

Method 2 (crontab)

  1. Create a folder for logs
mkdir /var/log/my-logs
  1. Create a bash file
touch /usr/local/bin/my-bash-file.sh
  1. Make it executable
chmod 700 /usr/local/bin/my-bash-file.sh
  1. Open the file and paste the following line, then save and exit.
/usr/local/lib/nodejs/my-current-node-version/bin/node /usr/local/bin/my-nodejs-file.js > /var/log/my-logs/run-script.$(date +%Y-%m-%d_%H-%M-%S).log
  1. Edit cron's file
crontab -e
  1. Paste the following line, then save and exit
0 */8 * * * root bash /usr/local/bin/my-bash-file.sh

This basically means that the command bash /usr/local/bin/my-bash-file.sh will be executed by user root at an interval of 0 */8 * * * (8 hours). Since my-bash-file.sh contains the command to run the Node.JS file the problem is be solved.

Some cron examples:

# Every 8 hours
0 */8 * * *

# Every 5 minutes
*/5 * * * *

# Every hour
0 * * * *

# Every Monday at 9:00 AM
0 9 * * MON

Sources: