Demystifing Node-Cron in Node Js.

Demystifing Node-Cron in Node Js.

Understanding how to use node-cron in node js

Table of contents

No heading

No headings in the article.

Hi, Guys… Today we’ll be discussing node-cron, a cron job in node js (the javascript backend framework). We would start from the basics, learning about node cron its meaning, what it's used for, and understanding how to use it especially in node js.

Node-Cron: The node-cron is a tiny task scheduler in pure JavaScript for nodejs .This module allows you to schedule tasks in nodejs . This can be used to monitor certain changes that happen on the server and what to do when those changes happen. A good example is an email scheduler, i.e sending love messages to all users in your database every Feb 14 telling them how well you love them.

It could be that you want to perform a charge authorization endpoint, (Paystack) charging endpoint on a particular user at a specific time or date.

Say we want to perform certain or different tasks at different times based on seconds, hours, days, weeks, years, etc. This explains the very need for node-cron.

var cron = require('node-cron');

cron.schedule('1,2,4,5 * * * *', () => {
  console.log('running every minute 1, 2, 4 and 5');
});

This above is the basic representation of how to run a node-cron in node js, but it doesn’t end there, right? you must have questions right now. Well, let's learn…

The represent seconds (0–59), minutes (0–59), hours (0–23), days of the month (1–31), months (1–12 (January, February, March …)), days of the week (0–7 (or names, Sunday, Monday)) respectively. Please note the last asterisk could be optional meaning the day of the week could be omitted.

# ┌────────────── second (optional)
 # │ ┌──────────── minute
 # │ │ ┌────────── hour
 # │ │ │ ┌──────── day of month
 # │ │ │ │ ┌────── month
 # │ │ │ │ │ ┌──── day of week (optional)
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *

We will go on to the different ways of formatting this scheduler to what suits your specific task and use. One helpful resource that you’d be needing to format dates and times to suit your specific task is Crontab guru.

Most often, I use this on the server to help me out with a lot of the stuff i have to do manually, but for me, I learned its usefulness, understood it, and gained mastery...

I guess you should do the same, cheers and until next time …