/

How to Set Up a Cron Job to Run a Node.js App

How to Set Up a Cron Job to Run a Node.js App

In this tutorial, I will guide you on how to set up a cron job that runs a Node.js app. Cron jobs are a time-based scheduler in Unix-like operating systems, which allow you to automate repeatable tasks. By following the steps below, you can configure a cron job to run your Node.js app at a specific time interval.

  1. Create a shell script file named run.sh with the following content:
1
2
#!/bin/sh
node app.js
  1. Grant execution rights to the run.sh file:
1
chmod +x run.sh
  1. Open the cron tab for editing:
1
crontab -e
  1. By default, this opens with the default editor (usually Vim). If you’re not familiar with Vim, enter insertion mode by pressing i to type/paste, then press esc followed by wq to save and quit.

  2. Now, you can add a new line for your cron job. The syntax for defining cron jobs can be intimidating, so I recommend using a website like Crontab Generator to help generate the cron expression without errors.

  3. Choose the desired time interval for your cron job and specify the command to execute. For example, let’s say you want to run the cron job every day at 10 AM. The generated crontab line will look like this:

1
0 10 * * * /Users/flaviocopes/dev/run.sh >/dev/null 2>&1
  1. Once you have added the cron job line, save and exit the editor.

  2. To verify that the cron job is successfully set up, you can view the list of active cron jobs by running the following command:

1
crontab -l
  1. If you want to remove a cron job, open the cron tab for editing again:
1
crontab -e

Remove the corresponding line, save, and exit the editor.

That’s it! You have now learned how to set up a cron job to run your Node.js app at a specific time interval. Enjoy the benefits of automating your tasks!

tags: [“cron job”, “Node.js”, “shell script”, “automation”]