Agenda简介
Agenda是一个定时任务管理模块,它将node中的定时任务存储在数据库中(官方文档推荐使用mongoDB),通过事件回调与监听实现定时任务调度。
使用步骤概述
总的来说分4步:
- 初始化(
new Agenda(..)
) - 定义任务(
agenda.define(..)
) - 配置任务(
agenda.every(..)
) - 最后设置事件监听(
agenda.on(..)
const Agenda = require('agenda')
const connection_options = {
db: {
address: 'mongodb://127.0.0.1:27017/agenda',
collection: 'agendaJobs',
options: { server: { auto_reconnect: true } },
},
}
// 初始化agenda
let agenda = new Agenda(connection_options)
agenda
.name('AGENDA TEST - ' + process.pid)
.defaultConcurrency(5)
.defaultLockLifetime(10000)
// 定义任务
agenda.define('updateCampaignTimeout', { priority: 'high', concurrency: 3 }, (job, done) => {
dbp_job.updateCampaignTimeoutTick()
.then(() => done())
.catch((error) => { throw error })
})
// 配置任务(需要在ready事件中完成)
agenda.on('ready', () => {
agenda.every('00 09 18 * * *', 'updateCampaignTimeout', {}, {timezone: 'Asia/Shanghai'})
console.log('agenda测试开始,启动完毕')
agenda.start()
})
// 设置监听
agenda.on('start', (job) => {
console.log('检测到job启动: ', job.attrs.name)
})
agenda.on('complete', (job) => {
console.log('检测到job完成: ', job.attrs.name)
})
agenda.on('success', (job) => {
console.log('检测到job成功: ', job.attrs.name)
})
agenda.on('fail', (job) => {
console.log('检测到job失败: ', job.attrs.name)
console.log('失败时间: ', job.attrs.failedAt)
console.log('失败原因: ', job.attrs.failReason)
agenda.stop()
})
// 最后,优雅的退出方案
function graceful() {
agenda.stop(() => {
console.log('检测到退出')
process.exit(0);
});
}
process.on(