Developing a web application includes various functions performed by triggering the API from the user interface. There are some scenarios where the functions need to be performed at regular intervals without any trigger from UI or API.
Cron job is specifically used for performing such functions that are scheduled to run at a given interval.

Example:
Let us discuss the usage of Cron job with an example. Consider an application portal where the status of the application needs to be changed to “Expired” when the due date mentioned in the application is crossed. Initially, the application will be in “Active” status till it meets the due date specified.

This can be handled using a Cron job where the due date in the applications are checked for its expiry.
To achieve this, we need a utility function to check the applications and filter them based on due date and the status “Active”. Then change their status to “Expired” and return the applications.


Next is to set up a cron job that can be scheduled to run the utility function at regular intervals for instance at midnight everyday.

Install the node-cron package using the command : yarn add node-cron.
Import the package inside the file where utility function needs to be called as given below:
import cron from “node-cron”;
Call the utility function using cron.scedule.


Here ‘0 0 * * *’ denotes that the cron job will run the function at every midnight(00:00).
Hence by this way, any task can be scheduled using Cron job to perform the functions at specific interval over the data in the database.

Leave a Reply