[Record 8] Vue+node+koa2+mysql+nginx+redis, full-stack development of small programs and administrator management system projects-use timing tasks to execute scripts

Foreword: The daily maintenance of the system must not rely on people to guard the computer 24 hours a day to operate the system; data synchronization, transaction flow verification, initial value of order numbers, etc., need to be done at night or when the system usage is lowest , To avoid data loss. For this reason, it is very important to choose a time for the system to automatically execute the script at that time. This section introduces timing execution scripts.

Download node-schedule dependency

yarn add node-schedule

Import and use

//app.js
const schedule = require('node-schedule')
const script = require('./util/script')
// 定义规则
let rule = new schedule.RecurrenceRule()
//每天的凌晨2点去执行了clearLogger方法(清除90天之前的日志)
rule.hour = 2
rule.minute = 0
rule.second = 0
// 启动任务
let job = schedule.scheduleJob(rule, () => {
    
    
  console.log('我在此时清除了日志哦:')
  console.log(new Date())
  script.clearLogger()
})
//script.js
const allServices = require('../controllers/mysqlConfig')
const common = require('./comon')

const script = {
    
    
  //清除90天之前的日志
  clearLogger() {
    
     
    let time_90=new Date().getTime() - 60*60*24*90*1000
    let _sql = `delete from logger where unix_timestamp(createtime)>='${time_90}'`
    allServices.query(_sql)
  }
}
module.exports=script

Here I put all the scripts in the script.js file, and clearLogger is the method used to clear the log.
For other timing task time settings, please refer to the document—> Timed task time settings

Previous: Generate request log
Next: To be written...

Guess you like

Origin blog.csdn.net/Smell_rookie/article/details/108969701