a blog for those who code

Thursday 2 January 2020

How to create Job Scheduler in Node.js

A job scheduler or a task scheduler is an application for creating a background program that will run on a specific time or interval to execute certain tasks. In this post, we will see how we can implement a job scheduler in node.js.

If you are from a Windows background, you might be familiar with Windows Service which is nothing but a background service that runs periodically to do some repetitive tasks like backing up files, taking server backup, or something like changing desktop background every day at 9 AM. This is where the Cron Jobs come into picture i.e. cron jobs help us to schedule a job periodically to do the actions that they are configured to do.

In one of my previous articles, we have gone through 2 Node.Js Task Scheduler and they were Cron and Agenda.

In this post, we will use another Node.js Job Scheduler library i.e. Node Cron. The node-cron module is a tiny task scheduler for node.js which allows you to schedule tasks in node.js using full crontab syntax. The basic example for creating the simple task scheduler in Node.js is shown below:

import cron from "node-cron";

cron.schedule('*/10 * * * *', () => {
  console.log('Runs every 10 minutes')

Now say you have a javascript file doTask.js which will do certain tasks, that you need to automate. The content of the doTask.js can be something like below where you are fetching the Rest API to get the data from the server and you want it to be automated every day:

// doTask.js

const getData = async () => {
  // get data from rest api

export default getData;

Now I need to set up the Task Scheduler which will run this getData every morning at 9 AM. To do that I will be writing a cron job as shown below :

import cron from "node-cron";
import getData from "./doTask";

cron.schedule('0 9 * * *', () => {
  console.log('Runs every day at 9 AM');

Thus the above cron scheduler in Node.js will run the getData function every day at 9 AM and thus our job is scheduled. You can use node-cron to schedule multiple jobs. So in this node.js cron tutorial we have learned how to schedule jobs / tasks using node-cron in Node.js.

No comments:

Post a Comment