在项目开发中,有许多场景需要执行一些定时任务,Egg 提供了一套机制来让定时任务的编写和维护更加优雅。
1. 定时上报应用状态。
2. 定时从远程接口更新本地缓存。
3. 定时进行文件切割、临时文件删除。
所有定时任务都统一存放在 app/schedule
目录下,每一个文件都是一个独立的定时任务,可以配置定时任务的属性和要执行的方法。
// app/schedule/updateCache.js
const Subscription = require('egg').Subscription;
class UpdateCache extends Subscription {
// 通过 schedule 属性来设置定时任务的执行间隔等配置
static get schedule() {
return {
// 执行时间间隔
interval: '5s',
// 指定所有的worker(进程)都需要执行
type: 'all',
// 是否禁用
disable: false
}
}
// 定时执行的操作
async subscribe() {
const res = await this.ctx.curl('http://www.api.com/cache', {
dataType: 'json',
});
this.ctx.app.cache = res.data;
}
}
module.exports = UpdateCache;
定时任务还可以这样简写。
// app/schedule/updateCache.js
module.exports = {
// 通过 schedule 属性来设置定时任务的执行间隔等配置
schedule: {
// 执行时间间隔
interval: '5s',
// 指定所有的worker(进程)都需要执行
type: 'all',
// 是否禁用
disable: false
},
// 定时执行的任务
async task(ctx) {
const res = await ctx.curl('http://www.api.com/cache', {
dataType: 'json',
});
ctx.app.cache = res.data;
}
}
有时候我们需要配置定时任务的参数,定时任务还有支持另一种写法。
// app/schedule/updateCache.js
module.exports = (app) => {
return {
// 通过 schedule 属性来设置定时任务的执行间隔等配置
schedule: {
// 执行时间间隔
interval: '5s',
// 指定所有的worker(进程)都需要执行
type: 'all',
// 是否禁用
disable: false
},
// 定时执行的任务
async task(ctx) {
const res = await ctx.curl('http://www.api.com/cache', {
dataType: 'json',
});
ctx.app.cache = res.data;
}
}
}
1. 定时方式
(1). interval
通过 schedule.interval
参数来配置定时任务的执行时机,定时任务将会每间隔指定的时间执行一次,interval 可以配置成:
A. 数字类型,单位为毫秒数,例如 5000
。
B. 字符类型,会通过 ms 转换成毫秒数,例如 5s
。
module.exports = {
schedule: {
// 每 10 秒执行一次
interval: '10s',
},
};
(2). cron
通过 schedule.cron
参数来配置定时任务的执行时机,定时任务将会按照 cron 表达式在特定的时间点执行,cron 表达式通过 cron-parser 进行解析。
注意:cron-parser 支持可选的秒( linux crontab 不支持 )
module.exports = {
schedule: {
// 每3小时准点执行一次
cron: '0 0 */3 * * *',
},
};
2. 执行类型
(1). worker
每台机器上只有一个 worker 会执行这个定时任务,每次执行定时任务的 worker 的选择是随机的。
(2). all
每台机器上的每个 worker 都会执行这个定时任务。
3. 其它参数
(1). cronOptions
配置 cron 的时区等,参见 cron-parser 文档。
(2). immediate
配置了该参数为 true 时,这个定时任务会在应用启动并 ready 后立刻执行一次这个定时任务。
(3). disable
配置该参数为 true 时,这个定时任务不会被启动。
(4). env
数组,仅在指定的环境下才启动该定时任务。