Home Web Front-end JS Tutorial How to implement scheduled tasks in NodeJs (detailed tutorial)

How to implement scheduled tasks in NodeJs (detailed tutorial)

Jun 22, 2018 pm 05:02 PM
node scheduled tasks

This article mainly introduces the sample code for implementing scheduled tasks in NodeJs. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

In the project, there is a function that is executed at 0 o’clock every day. I originally wanted to use setInterval to implement it, but I feel that this kind of demand will continue to exist in the future. Writing it yourself may not be scalable. high.

After searching, I found the node-schedule package.

Now record the usage method

node-schedule always executes specific methods by creating a new scheduleJob object.

The time value is expressed in the following table

*  *  *  *  *  *
┬  ┬  ┬  ┬  ┬  ┬
│  │  │  │  │  |
│  │  │  │  │  └ [dayOfWeek]day of week (0 - 7) (0 or 7 is Sun)
│  │  │  │  └───── [month]month (1 - 12)
│  │  │  └────────── [date]day of month (1 - 31)
│  │  └─────────────── [hour]hour (0 - 23)
│  └──────────────────── [minute]minute (0 - 59)
└───────────────────────── [second]second (0 - 59, OPTIONAL)
Copy after login

Use node-schedule to execute the method at the specified time

var schedule = require('node-schedule');
var date = new Date(2017, 11, 16, 16, 43, 0);

var j = schedule.scheduleJob(date, function(){
 console.log('现在时间:',new Date());
});
Copy after login

At 16:00 on December 16, 2017 43 minutes and 0 seconds, print the current time

Specify time interval execution method

var rule = new schedule.RecurrenceRule();
rule.second = 10;
var j = schedule.scheduleJob(rule, function(){
 console.log('现在时间:',new Date());
});
Copy after login

This is to print the time every time the number of seconds is 10. If you want to execute it every 10 seconds, just set rule.second =[0,10,20,30,40,50].

The values ​​supported by rule are second, minute, hour, date, dayOfWeek, month, year

Similarly:

Execution per second is rule.second =[0 ,1,2,3...59]
Execution for 0 seconds every minute is rule.second =0
Execution for 30 minutes every hour is rule.minute =30;rule.second =0;
Execution at 0 o'clock every day is rule.hour =0;rule.minute =0;rule.second =0;
....
At 10 o'clock on the 1st of each month, rule.date =1;rule .hour =10;rule.minute =0;rule.second =0;
0 o'clock and 12 o'clock on 1, 3, and 5 every week are rule.dayOfWeek =[1,3,5];rule.hour = [0,12];rule.minute =0;rule.second =0;
....

Example

1: Determine the time

For example: Execute

  var schedule = require("node-schedule");

  var date = new Date(2014,2,14,15,40,0);

  var j = schedule.scheduleJob(date, function(){

    console.log("执行任务");

  });
Copy after login

Cancel task at 15:40 on February 14, 2014

 j.cancel();
Copy after login

2: Fixed time every hour

For example: every hour 40-minute execution

  var rule = new schedule.RecurrenceRule();

  rule.minute = 40;

  var j = schedule.scheduleJob(rule, function(){

    console.log("执行任务");

  });
Copy after login

3: Execution at a certain time on certain days of the week,

For example: execution at 20:00 from Monday to Sunday

  var rule = new schedule.RecurrenceRule();

  rule.dayOfWeek = [0, new schedule.Range(1, 6)];

  rule.hour = 20;

  rule.minute = 0;

  var j = schedule.scheduleJob(rule, function(){

    console.log("执行任务");

  });
Copy after login

4 : Execution per second

  var rule = new schedule.RecurrenceRule();

  var times = [];

  for(var i=1; i<60; i++){

    times.push(i);

  }

  rule.second = times;

  var c=0;
  var j = schedule.scheduleJob(rule, function(){
      c++;
     console.log(c);
  });
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to use the video component to play videos in the WeChat mini program

How to use the audio component in the WeChat mini program

How to implement axios secondary encapsulation in vue

How to implement up and down scrolling announcements using js

The above is the detailed content of How to implement scheduled tasks in NodeJs (detailed tutorial). 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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Do you know some reasons why crontab scheduled tasks are not executed? Do you know some reasons why crontab scheduled tasks are not executed? Mar 09, 2024 am 09:49 AM

Summary of some reasons why crontab scheduled tasks are not executed. Update time: January 9, 2019 09:34:57 Author: Hope on the field. This article mainly summarizes and introduces to you some reasons why crontab scheduled tasks are not executed. For everyone Solutions are given for each of the possible triggers, which have certain reference and learning value for colleagues who encounter this problem. Students in need can follow the editor to learn together. Preface: I have encountered some problems at work recently. The crontab scheduled task was not executed. Later, when I searched on the Internet, I found that the Internet mainly mentioned these five incentives: 1. The crond service is not started. Crontab is not a function of the Linux kernel, but relies on a cron.

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

ThinkPHP6 scheduled task scheduling: scheduled task execution ThinkPHP6 scheduled task scheduling: scheduled task execution Aug 12, 2023 pm 03:28 PM

ThinkPHP6 scheduled task scheduling: scheduled task execution 1. Introduction In the process of web application development, we often encounter situations where certain repetitive tasks need to be executed regularly. ThinkPHP6 provides a powerful scheduled task scheduling function, which can easily meet the needs of scheduled tasks. This article will introduce how to use scheduled task scheduling in ThinkPHP6, and provide some code examples to help understand. 2. Configure scheduled tasks, create scheduled task files, and create a comman in the app directory of the project.

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Python implements automatic page refresh and scheduled task function analysis for headless browser collection applications Python implements automatic page refresh and scheduled task function analysis for headless browser collection applications Aug 08, 2023 am 08:13 AM

Python implements automatic page refresh and scheduled task function analysis for headless browser collection applications. With the rapid development of the network and the popularization of applications, the collection of web page data has become more and more important. The headless browser is one of the effective tools for collecting web page data. This article will introduce how to use Python to implement the automatic page refresh and scheduled task functions of a headless browser. The headless browser adopts a browser operation mode without a graphical interface, which can simulate human operation behavior in an automated way, thereby enabling the user to access web pages, click buttons, and fill in information.

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

How to perform task scheduling and scheduled tasks in PHP? How to perform task scheduling and scheduled tasks in PHP? May 12, 2023 pm 06:51 PM

In web development, many websites and applications need to perform certain tasks regularly, such as cleaning up junk data, sending emails, etc. In order to automate these tasks, developers need to implement task scheduling and timed task functions. This article will introduce how to implement task scheduling and timed tasks in PHP, as well as some commonly used third-party libraries and tools. 1. Task Scheduling Task scheduling refers to executing certain tasks according to specified times or events. In PHP, cron timer or similar mechanism can be used to implement task scheduling. Typically, task scheduling

How to use PHP to develop a scheduled refresh function for web pages How to use PHP to develop a scheduled refresh function for web pages Aug 17, 2023 pm 04:25 PM

How to use PHP to develop a scheduled refresh function for web pages. With the development of the Internet, more and more websites need to update display data in real time. Refreshing the page in real time is a common requirement, which allows users to obtain the latest data without refreshing the entire page. This article will introduce how to use PHP to develop a scheduled refresh function for web pages and provide code examples. The simplest way to implement scheduled refresh using Meta tag is to use HTML Meta tag to refresh the page regularly. In HTML&lt;head&gt;

See all articles