(一)egg-基础功能
一、定时任务
- (1)编写定时任务
所有的定时任务均放在app/shedule
目录下,每一个文件都是一个独立的定时任务,可以配置定时任务和要执行的方法。
例如:更新远程数据到内存缓存的定时任务,可以在app/schedule
目录下创建一个文件:
const Subscription = require('egg').Subscription;
class UpdateCache extends Subscription {
// 通过 schedule 属性来设置定时任务的执行间隔等配置
static get schedule() {
return {
interval: '1m', // 1 分钟间隔
type: 'all', // 指定所有的 worker 都需要执行
};
}
// subscribe 是真正定时任务执行时被运行的函数
async subscribe() {
const res = await this.ctx.curl('http://www.api.com/cache', {
dataType: 'json',
});
this.ctx.app.cache = res.data;
}
}
module.exports = UpdateCache;
//或者使用如下写法
module.exports = {
schedule: {
interval: '1m', // 1 分钟间隔
type: 'all', // 指定所有的 worker 都需要执行
},
//ctx可以调用service
async task(ctx) {
const res = await ctx.curl('http://www.api.com/cache', {
dataType: 'json',
});
ctx.app.cache = res.data;
},
};
上述定时任务会在每一个worker进程上每一分钟执行一次,将远程数据挂载在app.cache上。
- (2)定时方式
定时任务可以指定interval或者cron两种不同的定时方式。
interval:可以配置为数字或字符类型
cron:配置定时任务的执行时机&#x