SoFunction
Updated on 2025-03-10

Detailed explanation of the use of node-schedule module for setting timing tasks

node-schedule is one ofTimed tasks (crontab)Module. We can use timed tasks to maintain the server system, allowing it to perform certain necessary operations in a fixed time period, and can also use timed tasks to send emails, crawl data, etc.;

1. Installation

npm install node-schedule
# oryarn add node-schedule

2. Basic usage

use()You can create a timed task, a simple example to get started:

const schedule = require('node-schedule');

// Execute tasks when the current second value is 10, such as: 2018-7-8 13:25:10let job = ('10 * * * * *', () => {
 (new Date());
});

How to run the example? (First make sure to install it)

1. Create a new *.js file, such as:, paste the sample code;

2. Terminal (or command line)cdGo to the directory where the current file is located;

3. Terminal executionnode Execute code;

4、consoleIt will directly output content on the terminal interface;

5、Ctrl + CExecution can be exited;

The time value is expressed in the table below

*  *  *  *  *  *
┬  ┬  ┬  ┬  ┬  ┬
│  │  │  │  │  |
│  │  │  │  │  │  └ Day of the week, value: 0 - 7, where 0 and 7 both represent Sunday
│  │  │  └─── Month, value: 1 - 12
│  │  └─────────Date, value: 1 - 31
│  │  └───────────────────────────────────────────────────────────────────────────────�
│  └─────────────────────────────────────────────────────────────────────────────────�
└───────────────────────────────────────────────────────────────────────────────────�

You can also specify a specific time, such as:

const schedule = require('node-schedule');

// Define a future timelet date = new Date(2016, 6, 13, 15, 50, 0);

// Define a tasklet job = (date, () => {
 (new Date());
});

3. Advanced usage

In addition to basic usage, we can also use some more flexible methods to implement timing tasks.

3.1. Execute once a while

const schedule = require('node-schedule');

// Define ruleslet rule = new ();
 = [0, 10, 20, 30, 40, 50]; // Execute every 10 seconds
// Start the tasklet job = (rule, () => {
 (new Date());
});

ruleSupported setting values ​​aresecondminutehourdatedayOfWeekmonthyearwait. Some manufacturers use it, such as:

Execute every second

 = [0,1,2,3......59];

Execute in 0 seconds per minute

 = 0;

Execute at 30 minutes per hour

 = 30;
 = 0;

Perform at 0 o'clock every day

 =0;
 =0;
 =0;

Execute at 10 o'clock on the 1st of each month

 = 1;
 = 10;
 = 0;
 = 0;

Perform every Monday, Wednesday and Friday at 0:00 and 12:00

 = [1,3,5];
 = [0,12];
 = 0;
 = 0;

4. Cancel the task

Availablecancel()Terminates a running task.

();

This is the article about setting timing tasks: the use of node-schedule module. For more related setting timing tasks: the use of node-schedule module, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!