Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 2, 2021 10:36 pm GMT

How to setup scheduled cron jobs in Node.js

In this tutorial youll 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.

Lets first setup our project by running the following commands :

mkdir cron-jobscd cron jobsnpm init -y
Enter fullscreen mode Exit fullscreen mode

Well 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
Enter fullscreen mode Exit fullscreen mode

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");});
Enter fullscreen mode Exit fullscreen mode

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.

Heres 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)| | | | | | | | | | | |* * * * * *
Enter fullscreen mode Exit fullscreen mode

Schedule cron jobs daily/weekly/monthly

Run at midnight every day:

cron.schedule("0 0 * * *", () => {    // task to run daily});
Enter fullscreen mode Exit fullscreen mode

Run every Sunday at midnight:

cron.schedule("0 0 * * 0", () => {    // task to run weekly});
Enter fullscreen mode Exit fullscreen mode

Run on the first day of every month at midnight:

cron.schedule("0 0 1 * *", () => {    // task to run monthly});
Enter fullscreen mode Exit fullscreen mode

If youre 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:

Alt Text

Thats 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!


Original Link: https://dev.to/michaelburrows/how-to-setup-scheduled-cron-jobs-in-node-js-4926

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To