Egg 定时任务
高级架构图
定时任务
新建
在 app 目录下新建app/schedule
目录,在schedule
目录下新建get_time.ts
文件
js
const Subscription = require("egg").Subscription;
class GetTime extends Subscription {
static get schedule() {
return {
// 要是想 0 */3 * * * * 每隔3分钟执行一次
// 要是想 0 0 */3 * * * 每隔3小时执行一次
// 要是想 0 0 0 */3 * * 每隔3天执行一次
cron: "0/3 * * * * *", //第一个代表秒 第二个代表分钟 第三个代表小时 第四个代表天 第五个代表月 第六个代表星期几
//interval: "3s", // 1m 代表1 分钟间隔 3s 代表3秒间隔
// 级别worker比all低
//, all就是不管进程执行不执行 都会执行
// 每台机器上只有一个 worker 会执行这个定时任务,每次执行定时任务的 worker 的选择是随机的。
type: "worker",
};
}
async subscribe() {
const { ctx } = this;
ctx.app.logger.info("定时任务执行了");
console.log(Date.now());
}
}
module.exports = GetTime;
直接运行命令
js
npm run dev