Table of Contents
使用 node-cron
任务调度语法
选项
任务调度提示和技巧
定时任务方法
开始任务
停止任务
销毁任务
Home Web Front-end JS Tutorial How to use node-cron to schedule tasks in Node.js?

How to use node-cron to schedule tasks in Node.js?

Aug 25, 2021 am 10:13 AM
node.js

How to use node-cron to schedule tasks in Node.js?

No developer wants to spend all their time on tedious tasks such as system maintenance and administration, daily database backups, and regular downloads of files and emails. You'd rather focus on productive work rather than keeping track of when those annoying chores need to be done. [Recommended learning: "nodejs Tutorial"]

At this time, you need to use Task Scheduling, which will help you solve such problems.

Task Scheduling Enables you to schedule arbitrary code (methods/functions) and commands to be executed once at a fixed date and time, at a recurring interval, or after a specified interval. In Linux operating systems, task scheduling is typically handled at the operating system level by utility services such as cron.

In Node.js applications, functions similar to cron can be implemented using packages like node-cron. As introduced by the developer, node-cron is a micro-task scheduler in pure JavaScript for node.js based on GNU crontab.

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

Recommended tools

crontab editor: Online tools can visually generate crontab configuration files.

crontab syntax is as follows:

 # ┌────────────── second (可选)
 # │ ┌──────────── 分钟 (minute,0 - 59)
 # │ │ ┌────────── 小时 (hour,0 - 23)
 # │ │ │ ┌──────── 一个月中的第几天 (day of month,1 - 31)
 # │ │ │ │ ┌────── 月份 (month,1 - 12)
 # │ │ │ │ │ ┌──── 星期中星期几 (day of week,0 - 6) 注意:星期天为 0
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *
Copy after login

Allowed cron values ​​include the following.

1–311–12 (or month abbreviation Jan, Feb...)0–7 (or Jan, Feb..., 0 or 7 is Sunday)

下面我们来看看它的一些用法和用例。

使用 node-cron

使用 npm 安装 node-cron 模块。

$ npm install --save node-cron
Copy after login

任务调度语法

cron.schedule(cronExpression: string, task: Function, options: Object)
Copy after login

选项

  • scheduled:一个布尔值(boolean),用于设置创建的任务是否已安排(默认值为 true)。
  • timezone:用于任务调度的时区。有关有效值,可参考 moment-timezone

看看下面的例子。

const cron = require('node-cron')

cron.schedule('5 * * * * *', () => {
  console.log('每分钟在第 5 秒运行一个任务')
})
Copy after login

时间规范的位置 2、3、4、5 和 6 中的星号(*)类似于用于时间划分的文件 glob 或通配符;它们分别指定每分钟每小时每月的每一天每月和每周的每一天

以下代码将在每天凌晨 5:30 运行。

const cron = require('node-cron')

cron.schedule('30 5 * * *', () => {
  console.log('每天凌晨 5:30 运行任务')
})
Copy after login

任务调度提示和技巧

现在我们已经了解了基本知识,让我们做一些更有趣的事情。

假设您希望在每周五下午 4 点运行一项特定任务。代码如下所示:

const cron = require('node-cron')

cron.schedule('0 16 * * friday', () => {
  console.log('每周五下午 4:00 运行任务')
})
Copy after login

或者,您可能需要每季度运行一次数据库备份。crontab 语法没有一个月的最后一天选项,因此您可以使用下个月的第一天,如下所示。

const cron = require('node-cron')

cron.schedule('2 3 1 1,4,7,10 *', () => {
  console.log('在每个季度的第一天运行任务')
})
Copy after login

下面显示的任务在上午 10:05 到下午 6:05 之间每小时运行五分钟。

const cron = require('node-cron')

cron.schedule('5 10-18 * * *', () => {
  console.log('在上午 10 点到下午 6 点之间每小时运行五分钟的任务')
})
Copy after login

在某些情况下,您可能需要每两小时、三小时或四小时运行一次任务。您可以通过将小时数除以所需的时间间隔来完成此操作,例如,每四小时 *4,或在上午 12 点到下午 12 点之间每三小时运行 0-12/3

分钟也可以用同样的方法划分。例如,minutes 位置的表达式为 */10,表示每10分钟运行一次任务

下面的任务在上午 8 点到下午 5:58 之间每两小时运行五分钟。

const cron = require('node-cron')

cron.schedule('*/5 8-18/2 * * *', () => {
  console.log('在上午 8 点到下午 5:58 之间每两小时运行一次任务。')
})
Copy after login

定时任务方法

在结束之前,让我们关注一下三个关键的定时任务方法。

开始任务

scheduled 选项值设置为 false 时,任务将被调度,但无法启动,即使 cron 表达式正在滴答作响。

要启动这样的任务,您需要调用 start 方法。

const cron = require('node-cron')const task = cron.schedule('*/5 8-18/2 * * *', () => {
  console.log('在上午 8 点到下午 5:58 之间每两小时运行一次任务。')
})

task.start()
Copy after login

停止任务

如果需要停止任务运行,可以使用 stop 方法将 scheduled 选项设置为 false。除非重新启动,否则不会执行该任务。

const cron = require('node-cron')const task = cron.schedule('*/5 8-18/2 * * *', () => {
  console.log('在上午 8 点到下午 5:58 之间每两小时运行一次任务。')
})

task.stop()
Copy after login

销毁任务

destroy 方法停止任务并将其完全销毁。

const cron = require('node-cron')const task = cron.schedule('*/5 8-18/2 * * *', () => {
  console.log('在上午 8 点到下午 5:58 之间每两小时运行一次任务。')
})

task.destroy()
Copy after login

以上便是 node-cron 的大部分功能,您应该使用这些功能来安排频繁运行的任务。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of How to use node-cron to schedule tasks in Node.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".

See all articles
FieldValue
second0–59
minute0–59
hour0–23
##day of the month
month
day of the week