eggJS 后端定时任务

5 篇文章 0 订阅
5 篇文章 0 订阅

编写定时任务

所有的定时任务都统一存放在 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是真的好用】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值