eggJS 後端定時任務

編寫定時任務

所有的定時任務都統一存放在 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是真的好用】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章