Node.js使用node-schedule实现定时任务

背景:最近开发的一个后台管理系统中,需要每天凌晨12点更新登陆状态(将已登录改为未登陆),查找了许久发现了node-schedule这一神器
传送门:https://github.com/node-schedule/node-schedule

  • 安装
npm install node-schedule
  • 用法 用法有两种,一种是Cron风格定时器,另一种是对象文本语法定时器

    1、 Cron风格定时器

规则参数讲解 *代表通配符

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

6个占位符从左到右分别代表:秒、分、时、日、月、周几
*表示通配符,匹配任意,当秒是*时,表示任意秒数都触发,其它类推

参数讲解示例

每分钟的第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 schedule = require('node-schedule')  //  引入node-schedule
const  scheduleCronstyle = ()=>{
    //  每天的凌晨12点执行
    schedule.scheduleJob('0 0 0 * * *',()=>{
        console.log('scheduleCronstyle:' + new Date())
    //  每周一凌晨12点执行
    schedule.scheduleJob('0 0 0 * * 1',()=>{
        console.log('scheduleCronstyle:' + new Date())
    })
}
scheduleCronstyle()  //  调用函数

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

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

2、对象文本语法定时器

const schedule = require('node-schedule')  //  引入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()

3、取消定时器 调用定时器对象的cancl()方法

代码示例

const schedule = require('node-schedule')  //  引入node-schedule
function scheduleCancel(){
    let counter = 1
    const j = schedule.scheduleJob('* * * * * *', function(){
        console.log('定时器触发次数:' + counter)
        counter++
    })
    setTimeout(function() {
        console.log('定时器取消')
      //  定时器取消
        j.cancel()
    }, 5000)
}
scheduleCancel()

至此,该模块的功能已经实现,对node-schedule也有了新的认识

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在实际开发项目中,会遇到很多定时任务的工作。比如:定时导出某些数据、定时发送消息或邮件给用户、定时备份什么类型的文...
    流川枫丶阅读 7,215评论 2 4
  • 1. 前言 在实际开发项目中,会遇到很多定时任务的工作。比如:定时导出某些数据、定时发送消息或邮件给用户、定时备份...
    cbw100阅读 3,186评论 0 1
  • 在实际开发项目中,会遇到很多定时任务的工作。比如:定时导出某些数据、定时发送消息或邮件给用户、定时备份什么类型的文...
    四月天__阅读 99,414评论 4 34
  • 一点知识 在JAVA开发领域,目前可以通过以下几种方式进行定时任务: Timer:jdk中自带的一个定时调度类,可...
    雅倩兰爸爸阅读 3,860评论 1 28
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,145评论 1 32