编写定时任务
所有的定时任务都统一存放在 app/schedule
目录下,每一个文件都是一个独立的定时任务,可以配置定时任务的属性和要执行的方法。
一个简单的例子,我们定义一个定时网页转pdf的定时任务,就可以在 app/schedule
目录下创建一个 outputPDF.js
文件
const Subscription = require('egg').Subscription;
// const DateFormat = require('dateformat-util');
class outputPDF extends Subscription {
constructor(props) {
super(props);
this.count = 0;
}
// 通过 schedule 属性来设置定时任务的执行间隔等配置
static get schedule() {
return {
// cron: `0 10 6 11 9 * 2018`,
interval: '5s',
type: 'all',
immediate: false,
// disable: process.env.RUN_ENV != 'EWS', // 本地开发环境不执行
};
}
// subscribe 是真正定时任务执行时被运行的函数
async subscribe() {
const { ctx } = this;
//执行数据处理业务
console.log("定时任务global.topdf_working: ",global.topdf_working);
if(!global.topdf_working){
await ctx.service.cardService.outputpdf();
}
}
}
module.exports = outputPDF;
还可以简写为
module.exports = {
schedule: {
// cron: `0 10 6 11 9 * 2018`,
interval: '5s',
type: 'all',
immediate: false,
// disable: process.env.RUN_ENV != 'EWS', // 本地开发环境不执行
},
async task(ctx) {
//执行数据处理业务
console.log("定时任务global.topdf_working: ",global.topdf_working);
if(!global.topdf_working){
await ctx.service.cardService.outputpdf();
}
},
}
定时任务需要使用cron来配置定时器,参考:https://www.cnblogs.com/javahr/p/8318728.html
官方文档也有详细文档【egg是真的好用】