Scheduling Tasks with Cron Jobs

Cron Jobs are used for scheduling tasks to run on the server. They’re most commonly used for automating system maintenance or administration. However, they are also relevant to web application development. There are many situations when a web application may need certain tasks to run periodically.

Definitions

First let’s familiarize ourselves with the terms related to this subject.

“Cron” is a time-based job scheduler in Unix-like operating systems (Linux, FreeBSD, Mac OS etc…). And these jobs or tasks are referred to as “Cron Jobs”.

There is a cron “daemon” that runs on these systems. A daemon is a program that runs in the background all the time, usually initiated by the system. This cron daemon is responsible for launching these cron jobs on schedule.

The schedule resides in a configuration file named “crontab”. That’s where all the tasks and their timers are listed.

Why Use Cron Jobs?

Server admins have been using cron jobs for a long time. But since the target audience of this article is web developers, let’s look at a few use cases of cron jobs that are relevant in this area:

  • If you have a membership site, where accounts have expiration dates, you can schedule cron jobs to regularly deactivate or delete accounts that are past their expiration dates.
  • You can send out daily newsletter e-mails.
  • If you have summary tables (or materialized views) in your database, they can be regularly updated with a cron job. For example you may store every web page hit in a table, but another summary table may contain daily traffic summaries.
  • You can expire and erase cached data files in a certain interval.
  • You can auto-check your website content for broken links and have a report e-mailed to yourself regularly.
  • You can schedule long-running tasks to run from a command line script, rather than running it from a web script. Like encoding videos, or sending out mass e-mails.
  • You can even perform something as simple as fetching your most recent Tweets, to be cached in a text file.

Install node-cron using npm:

$ npm install –save node-cron

Import node-cron and schedule a task:

var cron = require('node-cron'); 
cron.schedule('* * * * *', function(){
  console.log('running a task every minute');
});

Cron Syntax

This is a quick reference to cron syntax and also shows the options supported by node-cron.

Allowed fields

 # ┌────────────── second (optional)
 # │ ┌──────────── minute
 # │ │ ┌────────── hour
 # │ │ │ ┌──────── day of month
 # │ │ │ │ ┌────── month
 # │ │ │ │ │ ┌──── day of week
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *

Allowed values

field

value

second

0-59

minute

0-59

hour

0-23

day of month

1-31

month

1-12 (or names)

day of week

0-7 (or names, 0 or 7 are sunday)

Using multiples values

You may use multiples values separated by comma:

var cron = require('node-cron');
 
cron.schedule('1,2,4,5 * * * *', function(){
  console.log('running every minute 1, 2, 4 and 5');
});

Using ranges

You may also define a range of values:

var cron = require('node-cron');
 
cron.schedule('1-5 * * * *', function(){
  console.log('running every minute to 1 from 5');
});

Using step values

Step values can be used in conjunction with ranges, following a range with ‘/’ and a number. e.g: 1-10/2 that is the same as 2,4,6,8,10. Steps are also permitted after an asterisk, so if you want to say “every two minutes”, just use */2.

var cron = require('node-cron');
 
cron.schedule('*/2 * * * *', function(){
  console.log('running a task every two minutes');
});

Using names

For month and week day you also may use names or short names. e.g:

var cron = require('node-cron');
 
cron.schedule('* * * January,September Sunday', function(){
  console.log('running on Sundays of January and September');
});

Or with short names:

var cron = require('node-cron');
 
cron.schedule('* * * Jan,Sep Sun', function(){
  console.log('running on Sundays of January and September');
});

Cron methods

Schedule

Schedules given task to be executed whenever the cron expression ticks.

Arguments:

  • !string expression – Cron expression
  • !Function func – Task to be executed
  • boolean? immediateStart – Whether to start scheduler immediately after create.

ScheduledTask methods

Start

Starts the scheduled task.

var cron = require('node-cron');
 
var task = cron.schedule('* * * * *', function() {
  console.log('immediately started');
}, false);
 
task.start();

Stop

The task won’t be executed unless re-started.

var cron = require('node-cron');
 
var task = cron.schedule('* * * * *', function() {
  console.log('will execute every minute until stopped');
});
 
task.stop();

Destroy

The task will be stopped and completely destroyed.

var cron = require('node-cron');
 
var task = cron.schedule('* * * * *', function() {
  console.log('will not execute anymore, nor be able to restart');
});
 
task.destroy();

Validate

Validate that the given string is a valid cron expression.

var cron = require('node-cron');
 
var valid = cron.validate('59 * * * *');
var invalid = cron.validate('60 * * * *');