Skip to main content

Scheduling Tasks using Cron-Jobs in Node.js

Have you ever wanted to run your code on a specific time without your intervention? Maybe you wanted to generate a scheduled report or send emails on a specific time interval or maybe you wanted to automate a process you do every day at a specific time interval. Now, There ways you could achieve that one way could be asking someone else to run it for you. A different way would be to schedule a cronjob to run on a specific interval.

CRON in itself is a command on Unix-like operating system to create jobs or process which are executed at a specified time. Now, In Node we would be using node-cronpackage to make cron jobs.

Create a node project and Install Node-Cron using the below command.

npm init -y & npm i node-cron

Basic Node-Cron scheduled Program

var cron = require('node-cron');

cron.schedule('* * * * * *', () => {
    console.log('running a cron job every second');
});

If you run the above program it would print the message every second. As it is scheduled to run every second. Those asterisks represent the time value that this program is scheduled to run.

Let’s understand Cron Scheduling with a very simple example

Understanding CRON Expressions

As you can see we have 6 *(asterisks) that represent a certain portion of time. The first asterisks represents the second value and is in range [0-59] because that many we have in a minute. if you leave the value to be asterisks it would run every second . In fact the entire value out there means .Run this code Every second of Every minute of Every hour of Every day of Every month of Every Day of the week.

Remembering the above line in bold is very important as if you change any value to their numerical or text(We will see this later) Doesn’t mean it will run at that time interval. for example, if you use scheduling of say `5 * * * * *`. It does not mean run every 5 seconds but it rather means run this code on the 5th second of Every Minute of Every hour of Every day of Every month of Every day of the week.


Lets discuss the possible values for these astericks. If you try to use any other value outside the list of the possible allowed value. The node-cron package will throw you an error.

  • The first asterisks that represent seconds can have a value between 0-59. This asterisk is also optional.
  • The second asterisks that represent minute can have a value between 0-59.
  • The third asterisks that represent the hour can have values between 0-23.
  • The fourth asterisks that represent the day of the month can have a value between 0-31.
  • The fifth asterisks that represent the month can have either value between 1- 12 or the name of the month.
  • The sixth asterisks that represent the day of the week can have a value between 0-7(both o and 7 represent Sunday) or names of the day. 

In Case you are not sure whether your cron-expression is valid or not node-cron provides us with a method called validate which would return boolean values.The boolean values represent whether the cron expression is valid or not.

var isValid = cron.validate('* * * * *');

If the above function represents true than it means the expression is valid for scheduling.

Using Schedulers in different ways

Using Multiple values

cron.schedule('1,2,3,4,5,6,7,8,9,10 * * * * *', () => {
    console.log('running a cron job first 10 seconds of a minute');
});

The Node-Cron package allows you to use multiple values that are separated by commas to schedule a job. Now, remember the statement we discussed above. This would then say it would run every first, second, third, fourth…..tenth second of every minute of every hour of every day of the month every of month of every day of the week. In short, it means to run this code every first 10 seconds of a minute and this is exactly what it does.

You can do the above task by using ranges as well.

cron.schedule('1-10 * * * * *', () => {
    console.log(' running a cron job every second');
});

Now both the start and end value our inclusive it runs similarly to our scheduler defined above this. Now Node-Cron also gives you an option to define a constant gap to run your job say if you wanted to run a process between 1 to 30 seconds of every minute with a gap of say 3 sec you could use a range that specifies 1 to 30 seconds followed by ‘/’ and a number that specifies the gap between each successive run

cron.schedule('1-30/3 * * * * *', () => {
    console.log(' running a cron job every second');
});

The above code would run our process on the first 30 seconds of a minute with a gap of 3 seconds between each run. Now you can also use step with * that would mean to run a process every __(whatever place you are using at) with a gap of the number specified after ‘/’.

Scheduling Jobs with Name of days and Month.

cron.schedule('* * * * June Thursday,Friday', () => {
    console.log((++i)+' running a cron job every second');
});

Now, while I am writing this part it is 23:58 on the 4th of June which is Thursday. This schedule would make my code run every second of every hour of every minute of every day of the month of June on Thursday and Friday. Now, this would run every second for me till Friday ends which is due to start in around a minute.

You can also pass and additional options object to the schedule function that is

cron.schedule('* * * * June Thursday,Friday', () => {
    console.log((++i)+' running a cron job every second');
},{
    timezone:'Asia/Kolkata',
    scheduled:false
});

So we pass an optional object with parameter timezone that refers to the timezone we would be using. You can find the entire list of the accepted timezone here and a boolean value scheduled whose default value is true. If you set it to false you will have to manually start the job using the .start() .

Now we know how to create a scheduler but you may want to start or end a scheduler based on some event. In this case you may want to use the .start() and .stop() methods.

Using the start() function to start a cron job

var cron = require('node-cron');
var i=0;
var task = cron.schedule('* * * * June Thursday,Friday', () => {
    console.log((++i)+' running a cron job every second');
},{
    timezone:'Asia/Kolkata',
    scheduled:false
});


task.start();

Similarly you could stop the function there is also a destroy function the main difference between a stop and a destroy is that a stopped job could be resumed but the destroyed job can not be.

There was it How to scheduled cron jobs in Node.js. You can use the knowledge here to multiple places like scheduling emails to be sent, to getting scheduled reports of event occurring in your website all you have to do is to write the function to do the same and wrap it in the cron scheduler that would automate the process for you.


Comments

Popular posts from this blog

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...