美文网首页
Node.js使用node-schedule实现定时任务

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

作者: 小明同学喜欢熊 | 来源:发表于2019-12-26 01:06 被阅读0次

    背景:最近开发的一个后台管理系统中,需要每天凌晨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也有了新的认识

    相关文章

      网友评论

          本文标题:Node.js使用node-schedule实现定时任务

          本文链接:https://www.haomeiwen.com/subject/yxohoctx.html