Node.js time-based scheduling with Node Schedule

Node.js time-based scheduling with Node Schedule

Sometimes, you need to schedule things. In everyday life, this is a common task. For example, you might have a team meeting every Monday through Friday at 9:30AM. Or perhaps you call your parents every Sunday 20 minutes after the hour. Some people find it relaxing to play softball in the park the first Thursday of each month. These are all examples of scheduled tasks.

There may be times when you need to schedule one or more tasks in your Node.js application. The setTimeout function is reliable, but it executes once. The setInterval function is reliable, but you would need to write logic that manages this. For example under what conditions the schedule should stop? Or, what if you want a task to run 10 minutes after the hour, every March 1st? Leveraging the setInterval function requires complex date-parsing code. Also, the setInterval instance is constantly checking the date, unnecessary taking up processing cycles.

This is where node-schedule comes in. This Node.js module allows you to setup a scheduled task using a straightforward syntax. You will never need to worry about parsing dates or checking conditions. Node-schedule takes care of all that for you. You configure your schedule, and then run it.

To get started, clone the following git hub repository:

https://github.com/kevinchisholm/node-js-time-based-scheduling-with-node-schedule

(Instructions on how to run the code are available in the Git hub page.)

Example # 1:

'use strict';

var counter = 0,
    schedule = require('node-schedule'),
    taskSchedule = new schedule.RecurrenceRule();

taskSchedule.minute = 15;

function reportOnSchdeule () {
    //increment the counter
    counter++;

    //report that the scheduled task ran
    console.log('The scheduled task ran. This is iteration #: ' + counter);
}

schedule.scheduleJob(taskSchedule, reportOnSchdeule);

console.log('The schdule has been initialzed');

In example # 1, we have three variables: counter, schedule and taskSchedule. Let's focus on the second and third variables. The schedule variable is a reference to the node-schedule module. The taskSchedule variable is an instance of the schedule.RecurrenceRule class. In short, it represents a schedule object, which is where the details of our scheduled task takes place.

We set the taskSchedule.minute property to the number: 15. This number represents the minutes after the hour for each iteration of the schedules task. In other words: this task should run on the fifteenth minute after the hour. This happens every hour.

The reportOnSchdeule function contains the code executed on each iteration of the schedule. I this case, the task is a console.log statement that tells us that the task ran, and which iteration of that task ran. We track the iterations as we increment the counter variable every time the task runs. This is a simple example, but the goal here is to show how simple it is to create a scheduled task.

After defining the reportOnSchdeule function, we run the schedule.scheduleJob method. We pass two arguments to this method. The first argument is the schedule object: taskSchedule. The second argument is the function to run on each iteration: reportOnSchdeule.

The console.log statement at the end of the file lets us know that the code is running. This is just in case we have to wait a while for the fist iteration.

NOTE: Be sure to change the taskSchedule.minute property closer to the actual time. For example, if it is 2:20PM where you are now, then change the value to 22. This way you won't have to wait an hour to see the task run : - )

Example # 2:

'use strict';

var counter = 0,
    schedule = require('node-schedule'),
    taskSchedule = new schedule.RecurrenceRule();

taskSchedule.minute = [1,2,3,4,5];

function reportOnSchdeule () {
    //increment the counter
    counter++;

    //report that the scheduled task ran
    console.log('The scheduled task ran. This is iteration #: ' + counter);
}

schedule.scheduleJob(taskSchedule, reportOnSchdeule);

console.log('The schdule has been initialzed');

In example # 2, there is a different approach to the schedule. We set the taskSchedule.minute property to be an array of numbers. These numbers represent the minutes after the hour for each iteration of the schedules task. In other words: this task should run on the first, second, third fourth and fifth minutes after the hour. This happens every hour.

NOTE: When you run the code example on your computer, be sure to change the numbers in the array to that they are closer so the actual time. For example, if it is 2:20PM where you are now, then change the array to: [21, 22, 23, 24, 25].

When you run the first code example, you should see the message "The scheduled task ran. This is iteration #: XX" in your console every 60 seconds.

Other scheduling options

Examples # 1 and # 2 illustrate simple approaches to creating a schedule object. In both cases, we set the value of the minute property, specifying the minutes after the hour the task should run. There is nothing wrong with this at all, and if it is what you need, great! But there is much more power under the hood here. There are more options. Cron-style, Date-based, and Recurrence Rule scheduling are all supported. Also, object literal Syntax is available making life even easier.

Summary

The node-schedule module provides powerful options for scheduling in your Node.js applications. You will never need to write setTimeout or setInterval. Node-schedule does the majority of your work. If your application is more than trivial, you can wrap node-schedule in a custom module. This way, you can abstract this scheduling functionality. Regardless of how you chose to leverage it, the node-schedule module is a time-saver. It features simple syntax and reliable performance.

Author:

Kevin Chisholm http://blog.kevinchisholm.com/

Share This