业务中的主要作用

  • 定时上报任务状态 ,便于系统监控
  • 定时从远程接口更新数据
  • 定时处理文件(清除过期日志文件)

    上手

    新建文件夹 app/schedule ,该文件下都是定时任务
    还要用到 egg 中 Subscription
    app/schedule/get_info.js ```javascript ‘use strict’;

const Subscription = require(‘egg’).Subscription;

class getInfo extends Subscription { // 返回一个对象,并在其中对定时任务进行配置 static get schedule() { return { // 每三秒执行一次 interval: 3000, // all:每个worker进程都会执行该定时任务; worker:指定进程执行该任务 type: ‘worker’, }; } async subscribe() { const info = this.ctx.info; console.log(‘subscription’, info); } }

module.exports = getInfo;

``` 关于其中 this.ctx.info 是我自己写的一个插件
效果
image.png


interval 属性 只是单纯的每隔多少时间就执行一次
还有一个 cron 属性:文档。可以设置每个月或者每周的什么时候