egg.js学习记录:定时任务

2019/06/10

定时任务

官方文档: https://eggjs.org/zh-cn/basics/schedule.html

所有定时任务都要放在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 都需要执行
  },
  async task(ctx) {
    const res = await ctx.curl('http://www.api.com/cache', {
      dataType: 'json',
    });
    ctx.app.cache = res.data;
  },
};
  • 两种写法都支持generator functionasync function
  • task入参为ctx,匿名的Context实例

定时方式

可以用interval或者cron两种方式

interval

  • 数字类型,单位毫秒,例如1000
  • 字符类型,根据后面的字符转换,例如5s为五秒,5ms为5毫秒

cron

cron 表达式通过cron-parser进行解析。

PS:cron-parser 支持可选的秒(linux crontab 不支持)。

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    |
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, optional)

详细用法可以看 Spring Boot 笔记中的 定时任务

module.exports = {
  schedule: {
    // 每三小时准点执行一次
    cron: '0 0 */3 * * *',
  },
};

类型

  • worker 类型:每台机器上只有一个 worker 会执行这个定时任务,每次执行定时任务的 worker 的选择是随机的。
  • all 类型:每台机器上的每个 worker 都会执行这个定时任务。





github: https://github.com/Hikiy
作者:Hiki
创建日期:2019.06.10
更新日期:2019.06.10

(转载本站文章请注明作者和出处 Hiki

Post Directory