Node's method of implementing scheduled tasks: 1. Use setTimeOut and event events for management; 2. Sort all added events and calculate the time interval between the current time and the most recent event occurrence time; 3. Call Just set the callback with setTimeOut.
The operating environment of this tutorial: linux7.3 system, node18.4.0 version, Dell G3 computer.
How does node implement scheduled tasks?
node scheduled tasks (node-schedule module)
Realize a scheduled task every day at ten o'clock in the morning The function of updating the git code on the server at two points
app.js file under the koa2 framework
import schedule from 'node-schedule'; import updateCode from './controllers/hcpLan/fetch' const app = new Koa(); const router = new Router(); router.get( '/', (ctx, next) => { ctx.body = 'hello' }); app.use(router.routes()).use(router.allowedMethods()); let rule = new schedule.RecurrenceRule() /**每天的凌晨12点更新代码*/ rule.hour = 0 rule.minute = 0 rule.second = 0 /**启动任务*/ schedule.scheduleJob(rule, () => { updateCode.cloneRepo(); console.log('代码更新了!'); }) app.listen(3000)
node-schedule principle: Use setTimeOut and event events to manage and manage all added events Sort, and calculate the time interval between the current time and the most recent event occurrence time, and then call setTimeOut to set the callback. Generally speaking, there are two types of events, one is one-time and the other is periodic. The one-time task will end after being called, and the periodic task will be called continuously. When a periodic event is called, it will Generate the next periodic task based on the period, add it to the task list, and reorder it. At the end of each task call, the next task is calculated and prepared.
1. Setting the timer
node-schedule allows a variety of rules to implement timing
1. Cron style timer
* * * * * * ┬ ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ | │ │ │ │ │ └ 一周的星期 (0 - 7) (0 or 7 is Sun) │ │ │ │ └───── 月份 (1 - 12) │ │ │ └────────── 月份中的日子 (1 - 31) │ │ └─────────────── 小时 (0 - 23) │ └──────────────────── 分钟 (0 - 59) └───────────────────────── 秒 (0 - 59, OPTIONAL) var schedule = require('node-schedule'); //当分钟为42时,执行一个cron任务 var j = schedule.scheduleJob('42 * * * *', function(){ console.log('执行了!'); });
2.Date object Rule timer
var schedule = require('node-schedule'); var date = new Date('2017-09-26 22:00:00'); var j = schedule.scheduleJob(date, function(){ console.log('执行了!'); });
3.RecurrenceRule instance rule timer
var schedule = require('node-schedule'); var rule = new schedule.RecurrenceRule(); rule.minute = 42; var j = schedule.scheduleJob(rule, function(){ console.log('执行了!'); });
For specific usage, please view the github documentation https://github.com/node-schedule/node-schedule
Recommended learning: "nodejs video tutorial"
The above is the detailed content of How to implement scheduled tasks in node. For more information, please follow other related articles on the PHP Chinese website!