Creating cronjob with Nodejs

Hey guys, Hope you are doing well. So i was planning to write a blog on creating cronjobs with nodejs so here it is.

What are CronJobs ?

So cronjobs are basically used in every production level projects. These are the task that run separately on a specific time. Like for example you what to backup your database every day. You can setup a cronjob that runs everyday backing up your database without disrupting your code. Or you can setup a cronjob to send Holiday greeting for all you users. So lets get started. The cronJob is given a cron Time pattern which indicates when the job has to run. The pattern is composed of six parts which are :

  • Seconds: 0-59
  • Minutes: 0-59
  • Hours: 0-23
  • Day of Month: 1-31
  • Months: 0-11
  • Day of Week: 0-6

i came across a website www.crontab.guru it creates a cron pattern for you if you are confused or have problem creating a cron pattern.

Project Structure

So below is the project structure.

Config : Config directory contains the configuration for the project.
Routes : Routes directory contains the route for the projects.
Jobs : Jobs directory will contains the cronjobs.
Server.js : Main server file.

Alright lets install the dependencies which we will need for the project by running the following command in your project directory.

we will be using express for setting up the server and for routing. Morgan is used for logging purposes. For cronjobs we will use cron which one of the best node modules available. Here is cron github page.

Once we have installed the dependencies lets setup the server open the config.js write the following code.

We have configured the server port on 3000 and added the timezone for the server. Now open the server.js and write the following code.

We required the express morgan cron and the configuration for the server. Used the morgan for logging and and started server on the port specified in the configuration. i.e 3000

Now create a new file called “hello.js’ in Jobs directory and add the following code in it.

don’t worry if you don’t understand it lets break it down bit by bit.

We are exporting a  function that takes two parameters cron and config.

We created two simple functions for printing the number and increasing it by 1. And  for resetting it.

We are creating our first cronjob.  cron.CronJob()  takes an object as a parameter to create a cronJob. Here are the properties of the object.

cronTime (Required) :  This is a required property it takes the cron time pattern. Its the time you want your job to run. In our case the cronjob will after run every 2 seconds daily.

onTick (Required) : This is also the required property. Its a function that runs whenever the time condition is met.

onComplete(Optional) : This is an optional property it runs when the cronjob has stopped. After finishing its task.

start (Optional) : This is a boolean. it means to activate the job immediately once its created so it can start comparing the time condition and tick and whenever it matches. If set to false then you will have to manually start the job. Default is false.

timeZone (Optional) : Its an optional property it takes a timezone and match the time pattern according to the relative to timezone.

And then we return the job Object which was created.

Now lets require the job in server.js so it can start running when we  boot up the server. Open server.js and paste this below the app.use(morgan(‘dev’)); like this :

Notice how we passed the cron and config parameters which were required by our hello.js module.

Now run the server by running the command “node server” and see the job printing the logs.

Well we did it !. Its that simple to create a cronjob with nodejs. Now lets create one more cronjob this time we will set the Start option to false let us have control when to start the job.

 

Create a new file in jobs directory named “countJob.js” and paste the following code in it.

Notices it pretty much the same code except for the start option in CronJob() constructor. Now we will add this to our server.js file.

If you run the server now. it won’t run the count CronJob. Lets setup the routes to start and stop the jobs. open your routes.js file and add the following code to it.

Here we are exporting a function that takes 3 parameters. app, express and the countJob Object. Setting up our routes via router object and using the router in our app.

we setup the router and created two routes one for starting the countJob and one for stopping it. The cronJob Object have couple of  methods in which start and stop. Starts and stops the job respectively.

Lets add our routes in server.js. require the routes below the countJob like this.

Now run the Server. See that only helloJob logs will be printed until you hit the startcount route for starting it.

Well thats about it with cronJobs. See how simple it is to create a cronJob in nodejs. Now you can work your way into creating complex cronJobs which would perform various task for your project. I have uploaded all the code for this project in my git repo.

 

Until Next time 🙂 Have a good Day or Night 😀

1 thought on “Creating cronjob with Nodejs

Leave a Reply to Sibghat Ullah Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.