NodeJS定时任务 注:2023-4-28更新

时光凉忆 / 2023-04-28 / 原文

 

使用的node-schedule 设置定时任务

 

引入

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

 

参数解析

schedule.scheduleJob(* * * * * *)

接收六个参数,位置分别如下,如果不需要,填 * 号即可,* 代表通配符

6个占位符从左到右分别代表:秒、分、时、日、月、周几

*表示通配符,匹配任意,当秒是*时,表示任意秒数都触发,其它类推

*  *  *  *  *  *
┬  ┬  ┬  ┬  ┬  ┬

│  │  │  │  │  |

│  │  │  │  │  └ [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)

 

举例:

每分钟的第30秒,执行

schedule.scheduleJob('30 * * * * *', async () => {
  console.log("执行轮查任务")      
})

// 每分钟的第30秒触发: '30 * * * * *'
// 每小时的1分30秒触发 :'30 1 * * * *'
// 每天的凌晨1点1分30秒触发 :'30 1 1 * * *'
// 每月的1日1点1分30秒触发 :'30 1 1 1 * *'
// 2020年的1月1日1点1分30秒触发 :'30 1 1 1 2020 *'
// 每周1的1点1分30秒触发 :'30 1 1 * * 1'

每个参数还可以传入数值范围

const task1 = ()=>{
  //每分钟的1-10秒都会触发,其它通配符依次类推
  schedule.scheduleJob('1-10 * * * * *', ()=>{
    console.log('scheduleCronstyle:'+ new Date());
  })
}
task1()

 

 取消任务 (声明一个变量接收定时任务。执行 cancel() 即可)

const task = schedule.scheduleJob('1-10 * * * * *', ()=>{
   console.log('scheduleCronstyle:'+ new Date());
})
task.cancel()

  

 

 

不同环境下的列子

  • rule 规则 : 指定时间间隔执行方法
let rule = new schedule.RecurrenceRule();
rule.second = 10;
let Maturity = schedule.scheduleJob(rule, function(){
  console.log('现在时间:',new Date());
});

 

这是每当秒数为10时打印时间。如果想每隔10秒执行,设置 rule.second =[0,10,20,30,40,50]即可。

每天0点执行就是rule.hour =0; rule.minute =0; rule.second =0;

每月1号的10点就是rule.date =1;rule.hour =10;rule.minute =0;rule.second =0;

每周1,3,5的0点和12点就是rule.dayOfWeek =[1,3,5]; rule.hour =[0,12]; rule.minute =0; rule.second =0;

 

 

 

  • 对象风格
const schedule = require('node-schedule');
function scheduleObjectLiteralSyntax(){
    //dayOfWeek
    //month
    //dayOfMonth
    //hour
    //minute
    //second
      //每周一的下午16:11分触发,其它组合可以根据我代码中的注释参数名自由组合
    schedule.scheduleJob({hour: 16, minute: 11, dayOfWeek: 1}, function(){
        console.log('scheduleObjectLiteralSyntax:' + new Date());
    });
}
scheduleObjectLiteralSyntax();