歡迎您光臨本站 註冊首頁

在NodeJs中使用node-schedule增加定時器任務的方法

←手機掃碼閱讀     月球人 @ 2020-06-12 , reply:0

java中直接使用定時器類就行了,但是在node中就沒有這麼簡單了,只能使用setInterval或者setTimeout兩個方法來實現,但是太繁瑣了,搜索了之後發現node-schedule這個包,特意試用一下

版本

node版本12.16.2koa2版> 2.7.0

1. 安裝

npm insatll node-schedule -S

2. 使用方法

2-1. 調用格式

  // 任務名稱可以用中文,也可以用英文,但必須唯一  schedule.scheduleJob(`任務名稱`, `時間`, () => {  });

 

2-2. 時間格式

  • 每分鐘的第30秒觸發: '30 * * * * *'

  • 每小時的1分30秒觸發 :'30 1 * * * *'

  • 每天的凌晨1點1分30秒觸發 :'30 1 1 * * *'

  • 每月的1日1點1分30秒觸發 :'30 1 1 1 * *'

  • 2016年的1月1日1點1分30秒觸發 :'30 1 1 1 2016 *'

  • 每週1的1點1分30秒觸發 :'30 1 1 * * 1'

3. 在項目中使用

3-1. 建立schedule.js

  const schedule = require('node-schedule');  // 生成新的定時任務  let interval = async (options) => {   return new Promise((resolve) => {   // 這裡設定14天為一個循環週期   // 假如設定的日期是2020-06-08, 返回就是{year: 2020, month: 6, day: 22, hour: 8, min: 0}   let time14 = GetDateStr(options.maintain_time, 14)   console.log(`${options.unit_name}_${time14.year}-${time14.month}-${time14.day}`, `1-2 1 1 ${time14.day} ${time14.month} *`)   // 終止之前的定時任務   editMaintainTime(options)   // 按照固定格式,設定定時任務,這裡使用每條數據的唯一字段+定時任務時間,作為任務名稱存入定時任務列表中   / 任務名稱就是'名字_2020-6-22'   // 任務時間就是'1-2 1 1 22 6 *' ,意思是每年的6月22日的每小時的1秒~10秒觸發   schedule.scheduleJob(`${options.unit_name}_${time14.year}-${time14.month < 10 ? "0" + time14.month: time14.month}-${time14.day < 10 ? "0" + time14.day: time14.day}`, `1-10 * * ${time14.day} ${time14.month} *`, () => {   console.log(options,'The world is going to end today.' + new Date())   // 寫入你自己想在定時任務觸發的時候,想要執行的函數   });  }  // 刪除定時任務  let editMaintainTime = async (options) => {   console.log('options', options)   // 查看所有的定時任務   for (let i in schedule.scheduledJobs) {   console.error("任務刪除前:"+i);   }   // 終止之前的定時任務   console.log('終止的任務', `${options.alarm14}`)   if (schedule.scheduledJobs[`${options.alarm14}`]) {   schedule.scheduledJobs[`${options.alarm14}`].cancel();   }   // 查看剩下的定時任務   for (let i in schedule.scheduledJobs) {   console.error("任務刪除後:"+i);   }   // time.cancel()   console.log('刪除成功')  }  // 時間選擇  let GetDateStr = (maintain_time, AddDayCount) => {   var dd = new Date(`${maintain_time}`);   dd.setDate(dd.getDate() + AddDayCount); // 獲取AddDayCount天后的日期   var y = dd.getFullYear();    var m = dd.getMonth() + 1   var d = dd.getDate()   var h = dd.getHours()   var min = dd.getMinutes()   return {   year: y,   month: m,   day: d,   hour: h,   min: min,   }  }  const intervalControl = {   interval: interval  }  module.exports = intervalControl

 

3-2. 調用該方法

  const intervalControl = require('../util/schedule')    // options傳入{unit_name: '名字', maintain_time: '自己選擇的開始時間', alarm14: '上一次定時任務的任務名稱'}  // unit_name,無格式  // maintain_time:2020-06-08  // alarm14: 2020-06-22  intervalControl.interval(options)



[月球人 ] 在NodeJs中使用node-schedule增加定時器任務的方法已經有463次圍觀

http://coctec.com/docs/javascript/show-post-238257.html