📜 Egg 与 Midway 的定时任务

内蒙 中信银行 多银行系统经常不能使用。

所以对方要求做轮询来检查,就有了这次技术储备

Egg

一、新建项目

$ mkdir egg-schedule && cd egg-schedule
$ npm init egg --type=ts
$ npm i
$ npm run dev
1
2
3
4

二、新建目录及文件

定时任务都放在 app/schedule 下,但是默认工程模板并不会有这个目录。

所以需要新建。

然后在 app/schedule 创建一个 ts 文件,并填入如下内容

import { Subscription } from "egg";

export default class extends Subscription {
  static get schedule() {
    return {
      // 数字类型,单位 毫秒,例如 5000
      // 字符类型,会转换成毫秒,例如 5s
      interval: "3s",
      type: "all",
    };
  }

  async subscribe() {
    console.log("这是一个定时任务");
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

至此,一个定时器就完成了。

三、配置解析

static get schedule() {
        return {
           // ...
        }
    }
1
2
3
4
5

schedule 为配置

重点为 定时方式,分为

  • interval
  • cron

interval 将会每间隔指定的时间执行一次。

  • 数字类型,单位为毫秒数,例如 5000。
  • 字符类型,会通过 ms 转换成毫秒数,例如 5s。

cron 将会按照 cron 表达式在特定的时间点执行。

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    |
│    │    │    │    │    └ 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)
1
2
3
4
5
6
7
8
9

如:

// 每三小时准点执行一次
cron: "0 0 */3 * * *";
1
2

其他详见官方文档open in new window

Midway

Midway 的定时任务 是基于 Egg 的,详见官方文档open in new window

一、新建项目

npm v6 使用 npm init midway --type=web midway-schedule
npm v7 使用 npm init midway -- --type=web midway-schedule

二、新建目录及文件

定时任务一般存放在 src/schedule 目录下,也是需要自行创建。

而后在里面建立一个 ts 文件,并填入如下内容

import { Provide, Inject, Schedule, CommonSchedule } from "@midwayjs/decorator";
import { Context } from "egg";

@Provide()
@Schedule({
  interval: 2333, // 2.333s 间隔
  type: "worker", // 指定某一个 worker 执行
})
export class HelloCron implements CommonSchedule {
  @Inject()
  ctx: Context;

  // 定时执行的具体任务
  async exec() {
    // 如果需要使用ctx,就可以 this.ctx.xxx
    console.log("定时任务");
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

三、配置解析

有了 Egg 的基础,看这个配置其实就一目了然了。。。

@ 装饰器 确实让配置更佳优雅了。