Cron in JavaScript
Although JS does not have inbuilt functionality to allow scheduling features, many libraries can be incorporated into our projects to enable us to use scheduler-like functions, and these libraries which are particularly mostly used in the industry are the “node-cron and cron ” libraries.
Before jumping into the practical implementation of these libraries, let me just discuss the concept of a scheduler in programming.
In the vast and evergrowing world of Computer Science, schedulers have been an important part of efficiently executing tasks in multi-tasking environments and resource management in operating systems. Schedulers can be of various types such as Operating System schedulers and Task-oriented schedulers, etc.
The main purpose of a Scheduler is to schedule a task in the best possible and required manner, allocate resources, and perform and store a task in the scheduling queue, there are various cases where a scheduler can be implemented, take an example of scheduling our mail on a particular day and time (requires task scheduler). There can be a scenario where we want to apply a scheduler in our application, and hence we need to know how to do it.
In this example, I will be using node.js to apply a task scheduler which will execute a function on the specified time and will return an output.
I will use the node-cron library to achieve my goal.
Get Syed Kumail Rizvi’s stories in your inbox
Join Medium for free to get updates from this writer.
First, we need to install node-cron
After, successfully installing node-cron we need to require or import it in our .js file where you want to apply the task scheduler
Once, you have the required cron in your file, then write the functional logic which, you want to schedule, in my case the logic is to say Hello world and print Date.now()
Once you are done with your logic implementation, then comes the part of scheduling the task using cron.schedule() method. This method accepts a cron expression and a callback function, we can easily validate the cron expression using cron.validate() method which returns a boolean value, the schedule function can be applied like this.
The cron expression is like ( min, hrs, day, month, year ), and above (*) is used to indicate that execute the task() each minute.
On running this .js file using node command this output was observed at an interval of 1 min.
The cron object has many other functions such as getTasks() and validate() which are used to get an array of task objects that are scheduled and to validate the expression as per cron expression criteria respectively.
Hope, you are able to understand the concept of a task scheduler and how to implement it using the node-cron library.




