In this tutorial you’ll learn how to schedule cron jobs in Node.js. Typically cron jobs are used to automate system maintenance but can also be used for scheduling file downloads or sending emails at regular intervals.
Let’s first setup our project by running the following commands :
mkdir cron-jobs
cd cron jobs
npm init -y
We’ll be using the node-cron package which simplifies creating cron jobs in node.js using the full crontab syntax. Run the following command to install node-cron
:
npm install node-cron
With node-cron installed create a new index.js
file with a sample cron job that will run every minute:
var cron = require("node-cron");
cron.schedule("* * * * *", () => {
console.log("Running each minute");
});
The asterisks are part of the crontab syntax used to represent different units of time. Five asterisks represents the crontab default which will run every minute.
Here’s what unit of time each of the asterisks represent and the values allowed:
┌──────────────── second (optional 0 - 59)
| ┌────────────── minute (0 - 59)
| | ┌──────────── hour (0 - 23)
| | | ┌────────── day of month (1 - 31)
| | | | ┌──────── month (1 - 12)
| | | | | ┌────── day of week (0 - 7, 0 or 7 are sunday)
| | | | | |
| | | | | |
* * * * * *
Schedule cron jobs daily/weekly/monthly
Run at midnight every day:
cron.schedule("0 0 * * *", () => {
// task to run daily
});
Run every Sunday at midnight:
cron.schedule("0 0 * * 0", () => {
// task to run weekly
});
Run on the first day of every month at midnight:
cron.schedule("0 0 1 * *", () => {
// task to run monthly
});
If you’re struggling to understand exactly how the crontab syntax works check out crontab guru. This website provides a simple editor that displays the cron schedule based on the cron syntax you input:
That’s all for this tutorial. Hopefully you now know how to a setup a cron job to save time on things you may have done manually in the past. As always thanks for reading!
Top comments (5)
Great to see cron getting another outing. Have used that in all sorts of situations for years.
Have you ever used Cron so that users can schedule themselves?
No, however there's nothing to say that that can't be done. I've usually used it scheduling events on a server (sometimes despite the presence of SchTasks)
I want users to schedule Cron by themselves but have no idea yet
I have hours and minutes in mongodb when the user enters the time they want to use cron. So how do I install that time?