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.
- Create a shell script file named
run.sh
with the following content:
#!/bin/sh
node app.js
- Grant execution rights to the
run.sh
file:
chmod +x run.sh
- Open the cron tab for editing:
crontab -e
-
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 pressesc
followed bywq
to save and quit. -
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.
-
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:
0 10 * * * /Users/flaviocopes/dev/run.sh >/dev/null 2>&1
-
Once you have added the cron job line, save and exit the editor.
-
To verify that the cron job is successfully set up, you can view the list of active cron jobs by running the following command:
crontab -l
- If you want to remove a cron job, open the cron tab for editing again:
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!