search
HomeWeb Front-endJS TutorialHow to use node-cron to schedule tasks in 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
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *

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

任务调度语法

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

选项

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

看看下面的例子。

const cron = require('node-cron')

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

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

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

const cron = require('node-cron')

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

任务调度提示和技巧

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

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

const cron = require('node-cron')

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

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

const cron = require('node-cron')

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

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

const cron = require('node-cron')

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

在某些情况下,您可能需要每两小时、三小时或四小时运行一次任务。您可以通过将小时数除以所需的时间间隔来完成此操作,例如,每四小时 *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 之间每两小时运行一次任务。')
})

定时任务方法

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

开始任务

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

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

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

task.start()

停止任务

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

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

task.stop()

销毁任务

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

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

task.destroy()

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

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

Field Value
second 0–59
minute 0–59
hour 0–23
##day of the month
month
day of the week

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
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.