DEV Community

Sahil Thakur
Sahil Thakur

Posted on

How to schedule tasks in Node.js

This post is originally written here along with code samples and images -> https://easyontheweb.com/how-to-schedule-tasks-in-node-js/

I still remember when I first heard of the concept of cron-jobs and how to schedule tasks in general, not just in Node.js. The problem statement of having to run something again and again was always in my mind but till that point of time I actually did not ever need to have a scheduler in any of my projects. So, when the day finally came I was amazed at how easily it could actually be done.

So, in this article we’ll be discussing how we can schedule tasks in Node.js, what cron jobs are and also about a very cool NPM package called node-cron.

But, first let us just take a look at what scheduled tasks are and what problems we can solve by scheduling tasks. A scheduled task is something that runs periodically based on time intervals – this task is not dependent on an action occurring and then it being triggered to run but instead it solely depends on the time. For example, you might want to take a backup of your database every two hours – for that you can run a scheduled task and set it’s timing for two hours. Another case maybe that every night at 12 you might want to run some kind of analysis script on certain data of your application and update certain aggregate numbers for them.

Different applications may have different needs for scheduled tasks but if you ever come across a requirement in your application that makes you go like “Man, I wish think happened on it’s own every X hours” , that is an indication for you to schedule that task.

Cron-jobs
According to very informative HostGator article here – cron is a Linux utility which schedules a command or script on your server to run automatically at a specified time and date. A cron job is the scheduled task itself. Cron jobs can be very useful to automate repetitive tasks.

That pretty much is a very clear and concise introduction to cron jobs. Again, cron jobs are just a different name for scheduled tasks and the possibilities are really endless here, you may set up any script as a cron job on your server and it will be executed seamlessly (as long as you don’t botch up the script that is 😛 ).

Under the hood, there is cron daemon (background process) that controls the running of scripts at their scheduled time by looking at the crontab which is a table of scripts and their times.

Using node-cron to schedule tasks
First and foremost here is the link for the node-cron NPM package -> https://www.npmjs.com/package/node-cron

As we discussed before, there is a crontab that the system maintains and uses to run scripts at particular times. Now, this article is not on how you can schedule tasks in your linux system but how you can schedule tasks in Node.js . Nevertheless, a great thing is that the node-cron package actually uses the exact same scheduling syntax as the crontab one. Therefore, if you know how to do it at one place, you nearly know how to do it for the other one as well (in terms of syntax).

The node-cron module is a very lightweight and purely Javascript based scheduler that is super easy to use and does the job perfectly. Therefore, we’ll be using it to schedule our tasks in Node. Note that there are plenty of other packages that do the same as well but I just prefer node-cron for the ease of it’s use.

The crontab syntax
Before actually using the node-cron module in an application, I think it’s important to discuss the crontab syntax once as it is well… an interesting one least to say.

# ┌────────────── second (optional) (0-59)
# │ ┌──────────── minute (0-59)
# │ │ ┌────────── hour (0-23)
# │ │ │ ┌──────── day of month (1-31)
# │ │ │ │ ┌────── month (1-12)
# │ │ │ │ │ ┌──── day of week (0-7) 0 is sunday
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *
This is a diagram that can help you with the crontab syntax but to be honest no one actually memorises this stuff, you just google and find how to do it. But it’s good to have some familiarity with it at least.

A few examples of set up cron jobs
In the above image are some examples of how to work with the crontab syntax to set up cron jobs on particular times and dates.

Even though the syntax is simple it sometimes does mess up with your mind so what I would suggest is not overthinking it and just letting your instincts type the crontab syntax. NO ! Please google the crontab syntax to confirm it once 😛 I mess it up all the time myself.

node-cron in node.js application
First of all, we need to install the node-cron module into our application using npm / yarn.

npm install --save node-cron

Yes, it’s as easy as this ! This will schedule a cron for 5:00 AM every day which will console log this statement. But as it is very clear, the second argument is for you to provide a function as an argument that would carry out the task you want to schedule – maybe send a good morning email to someone at 5 ?

There’s an awful lot of crontab syntax that you could manipulate in order to achieve more fine grain control of how you want to schedule your jobs. A very cool tool that can help you out and generate the crontab syntax that you need is this here -> https://crontab-generator.org/

You might also want to explore the shelljs package so that you can it from within your node code to run commands on the terminal (something you need to do for many scheduled tasks, maybe taking a database backup ?).

This is a simple node script using which we are taking a backup of your sqlite database every night at 11:59 PM. We’re using the shelljs package to run the shell commands from within the node code.

The concept behind scheduled tasks and cron jobs is very powerful and yet we are able to execute them so easily thanks to the clean API provided by node-cron and a very cool crontab syntax. The applications for this are for you to think and well actually, dependent on what is needed in your app but now you know how easy it is to implement them !

If you liked this article and would like to see other cool articles on NodeJS check this link here -> https://easyontheweb.com/category/node/

Also, it would be great if you join this Facebook group with me and other web developers to interact and talk to ! -> https://www.facebook.com/groups/503230450489995

Top comments (2)

Collapse
 
garima2808 profile image
garima2808

Are you open to new job opportunity?

Collapse
 
masoodbinmohammad profile image
Masood Mohammad

Hi Sahil,
Thanks for your post...Indeed helpul.
Btw i sense that you have missed out a command that need to be in place after mentioning about installing the package?
Do correct me if i am wrong.