This is the 19th day of my participation in the August More Text Challenge

No developer wants to spend all his time on tedious tasks such as system maintenance and administration, daily database backups, and regular downloads of files and E-mail. You’d rather focus on productive work than keep track of when those annoying chores need to get done.

This is where task scheduling comes in, which helps you solve such problems.

Task scheduling enables you to schedule any code (methods/functions) and commands to execute once at a fixed date and time, at a repeated interval, or after a specified interval. In Linux, task scheduling is typically handled at the operating system level by utility services such as Cron.

In Node.js applications, cron-like functionality can be implemented using packages like Node-cron. As described by the developers, Node-Cron is a tiny task scheduler in node.js pure JavaScript based on GNU Crontab.

The crontab is a scheduled task executor in Linux. Cron operations are driven by the crontab file, which is a configuration file that contains instructions for the Cron daemon. The Node-cron module allows us to schedule tasks in Node using the full crontab syntax.

🎉 Recommendation Tool

Crontab editor: An online tool that visually generates crontab configuration files.

The crontab syntax looks like this:

 # chrysene ── second (optional)
 # │ chrysene ── minute (minute, 0-59)
 # │ chrysene ── hour (hour, 0-23)
 # │ │ chrysene ── Day of month, 1-31
 # │ │ chrysene ── month (month, 1-12)
 # │ │ │ chrysene ── Day of week, 0-6: Sunday 0
 # │ │ │ │ │
 # │ │ │ │ │
 # * * * * * *
Copy the code

The allowed CRon values include the following.

field value
second 0 to 59
minute 0 to 59
hour 0–23
day of the month 1–31
month 1 — 12 (or months abbreviated Jan, Feb…)
day of the week 0 — 7 (or Jan, Feb… , 0 or 7 is Sunday)

Let’s look at some of its uses and use cases.

Use the node – cron

Install the Node-cron module using NPM.

$ npm install --save node-cron
Copy the code

Task scheduling syntax

cron.schedule(cronExpression: string, task: Function.options: Object)
Copy the code

options

  • scheduled: a Boolean value (boolean) to set whether the created task is scheduled (the default istrue).
  • timezone: Time zone used for task scheduling. For valid values, refer tomoment-timezone.

Take a look at the following example.

const cron = require('node-cron')
​
cron.schedule('5 * * * * *'.() = > {
  console.log('Run a task at 5 seconds per minute')})Copy the code

The asterisks (*) in positions 2, 3, 4, 5, and 6 of the time specification are similar to globs or wildcards used for time division; They specify minute, hour, day of the month, month, and day of the week, respectively.

The following code will run every day at 5:30 am.

const cron = require('node-cron')
​
cron.schedule(5 * * *.() = > {
  console.log('Running tasks at 5:30 am every day')})Copy the code

Task scheduling tips and tricks

Now that we’ve covered the basics, let’s do something more interesting.

Suppose you want to run a specific task every Friday at 4 p.m. The code looks like this:

const cron = require('node-cron')
​
cron.schedule('0 16 * * friday'.() = > {
  console.log('Run missions every Friday at 4:00 PM')})Copy the code

Alternatively, you might want to run a database backup quarterly. The crontab syntax does not have the last day of a month option, so you can use the first day of the next month, as shown below.

const cron = require('node-cron')
​
cron.schedule('2, 3,1,4,7,10 *'.() = > {
  console.log('Run tasks on the first day of each quarter')})Copy the code

The tasks shown below run for five minutes every hour between 10:05 a.m. and 6:05 p.m.

const cron = require('node-cron')
​
cron.schedule('5 10-18 * * *.() = > {
  console.log('Run five minute tasks per hour between 10am and 6pm')})Copy the code

In some cases, you may need to run tasks every two, three, or four hours. You can do this by dividing the number of hours by the time interval required, for example, every four hours *4, or running 0-12/3 every three hours between 12 a.m. and 12 p.m.

Minutes can be divided in the same way. For example, the expression of the minutes position is */10, indicating that a task is run every 10 minutes.

The following tasks run for five minutes every two hours between 8 a.m. and 5:58 p.m.

const cron = require('node-cron')
​
cron.schedule('*/5 8-18/2 * * *'.() = > {
  console.log('Run tasks every two hours between 8 a.m. and 5:58 p.m. ')})Copy the code

Timed task method

Before we wrap up, let’s focus on three key timed task approaches.

Start task

When you set the Scheduled option value to false, the task will be scheduled but cannot start, even though the CRon expression is ticking.

To start such a task, you need to call the start method.

const cron = require('node-cron')
​
const task = cron.schedule('*/5 8-18/2 * * *'.() = > {
  console.log('Run tasks every two hours between 8 a.m. and 5:58 p.m. ')
})
​
task.start()
Copy the code

Stop the task

If you need to stop the task running, you can use the stop method to set the Scheduled option to false. This task will not be performed unless restarted.

const cron = require('node-cron')
​
const task = cron.schedule('*/5 8-18/2 * * *'.() = > {
  console.log('Run tasks every two hours between 8 a.m. and 5:58 p.m. ')
})
​
task.stop()
Copy the code

Destruction of the task

The destroy method stops the task and destroys it completely.

const cron = require('node-cron')
​
const task = cron.schedule('*/5 8-18/2 * * *'.() = > {
  console.log('Run tasks every two hours between 8 a.m. and 5:58 p.m. ')
})
​
task.destroy()
Copy the code

These are the main features of Node-Cron that you should use to schedule frequently running tasks.