@eggjs/schedule

中文文档
6.1.0发布于 2026/10/07MITTypeScriptES Module构建来源已验证近 30 天下载 5122

用于鸡蛋的调度插件,支持玉米工作.

中文使用文档
文档目录15 节
  1. 使用量
  2. 概览
  3. 任务
  4. 时间安排
  5. 重排时序
  6. 中间样式排程
  7. 计划类型
  8. 动态时间表
  9. 配置
  10. 日志
  11. 自定义目录
  12. 测试
  13. 问题和建议
  14. 许可证
  15. 贡献者

@eggjs/ 计划

NPM version Known Vulnerabilities npm download Node.js Version

彩蛋的调度插件, 默认启用了彩蛋的内置插件 .

它对于开发者来说是完全可扩展的,并且提供了简单的内置定时器战略.

使用量

只要将您的工作文件添加到 {baseDir}/app/schedule。 。 。 .

// {baseDir}/app/schedule/cleandb.ts
import { Subscription } from 'egg';

export default class CleanDB extends Subscription {
  /**
   * @property {Object} schedule
   *  - {String} type - schedule type, `worker` or `all` or your custom types.
   *  - {String} [cron] - cron expression, see [below](#cron-style-scheduling)
   *  - {Object} [cronOptions] - cron options, see [cron-parser#options](https://github.com/harrisiirak/cron-parser#options)
   *  - {String | Number} [interval] - interval expression in millisecond or express explicitly like '1h'. see [below](#interval-style-scheduling)
   *  - {Boolean} [immediate] - To run a scheduler at startup
   *  - {Boolean} [disable] - whether to disable a scheduler, usually use in dynamic schedule
   *  - {Array} [env] - only enable scheduler when match env list
   */
  static get schedule() {
    return {
      type: 'worker',
      cron: '0 0 3 * * *',
      // interval: '1h',
      // immediate: true,
    };
  }

  async subscribe() {
    await this.ctx.service.db.cleandb();
  }
}

您也可以简单地使用诸如:

import { EggContext } from 'egg';

export const schedule = {
  type: 'worker',
  cron: '0 0 3 * * *',
  // interval: '1h',
  // immediate: true,
};

export async function task(ctx: EggContext) {
  await ctx.service.db.cleandb();
}

概览

@eggjs/schedule 支持基于克龙的调度和基于间隔的调度.

附表决定由 agent 进程. agent 触发任务并向 worker 进程。 那么,一个或所有 worker 进程根据调度类型执行任务.

要设置调度任务, 只需在 {app_root}/app/schedule。一个文件包含一个任务和导出 schedule 财务报告和审定财务报表 task 属性.

拇指的规则是每个文件一个工作.

任务

任务是一个类,将随每个时间表即时进行 subscribe 将引用方法.

您可以获取匿名背景 this.ctx。 。 。 .

  • ctx.方法: SCHEDULE
  • ctx.path: (英语) /__schedule?path=${schedulePath}&${schedule}。 。 。 .

为了创造任务, subscribe 可以是生成器函数或合成函数。 例如:

// A simple logger example
import { Subscription } from 'egg';

export default class LoggerExample extends Subscription {
  async subscribe() {
    this.ctx.logger.info('Info about your task');
  }
}
// A real world example: wipe out your database.
// Use it with caution. :)
import { Subscription } from 'egg';

export default class CleanDB extends Subscription {
  async subscribe() {
    await this.ctx.service.db.cleandb();
  }
}

时间安排

schedule 是一个包含一个所需属性的对象, type,和可选属性, { cron, cronOptions, interval, immediate, disable, env }。 。 。 .

重排时序

使用 剪贴板。 。 。 .

说明: cron-parser 支助 second 作为不为 linux crontab 支持的可选.

@hourly / @daily / @weekly / @monthly / @yearly 也得到支持.

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    |
│    │    │    │    │    └ 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)

示例

// To execute task every 3 hours
export const schedule = {
  type: 'worker',
  cron: '0 0 */3 * * *',
  cronOptions: {
    // tz: 'Europe/Athens',
  },
};

中间样式排程

用于 setInterval,并提供支持 分钟 转换样式

示例

// To execute task every 3 hours
export const schedule = {
  type: 'worker',
  interval: '3h',
};

通知: Egg内置定时器战略将按固定速度安排每次执行,无论执行时间如何. 所以,你必须保证你的实际执行时间 task/subscribe 必须小于您的延迟时间 .

计划类型

内部支持是:

  • worker: 当一个调度运行时, 将用一个随机工执行 .
  • all: 在所有工人中执行时间表.

自定义时间表 :

要创建自定义时间表,只需扩展 agent.ScheduleStrategy 并登记到 agent.schedule.use(type, clz)。 。 。 . 您可以安排一个随机工人或所有工人执行的任务 内置方法 this.sendOne(...args) 或者说 this.sendAll(...args) 以物配主者, 它会传递给 subscribe(...args) 或者说 task(ctx, ...args)。 。 。 .

// {baseDir}/agent.ts
import { Agent } from 'egg';

export default (agent: Agent) => {
  class CustomStrategy extends agent.ScheduleStrategy {
    start() {
      // such as mq / redis subscribe
      agent.notify.subscribe('remote_task', (data) => {
        this.sendOne(data);
      });
    }
  }

  agent.schedule.use('custom', CustomStrategy);
};

那你可以用它来定义你的工作:

// {baseDir}/app/schedule/other.ts
import { Subscription } from 'egg';

export default class ClusterTask extends Subscription {
  static get schedule() {
    return {
      type: 'custom',
    };
  }

  async subscribe(data) {
    console.log('got custom data:', data);
    await this.ctx.service.someTask.run();
  }
}

动态时间表

// {baseDir}/app/schedule/sync.ts
import { Application } from 'egg';

export default (app: Application) => {
  class SyncTask extends app.Subscription {
    static get schedule() {
      return {
        interval: 10000,
        type: 'worker',
        // only start task when hostname match
        disable: require('os').hostname() !== app.config.sync.hostname,
        // only start task at prod mode
        env: ['prod'],
      };
    }

    async subscribe() {
      await this.ctx.sync();
    }
  }

  return SyncTask;
};

配置

日志

见 ${appInfo.root}/logs/{app_name}/egg-schedule.log 规定 配置、 海关。 。 。 .

// config/config.default.ts
import { EggAppConfig } from 'egg';

export default {
  customLogger: {
    scheduleLogger: {
      // consoleLevel: 'NONE',
      // file: path.join(appInfo.root, 'logs', appInfo.name, 'egg-schedule.log'),
    },
  },
} as Partial<EggAppConfig>;

自定义目录

如果您想要添加额外的调度目录, 您可以使用此配置 .

// config/config.default.ts
import { EggAppConfig } from 'egg';

export default {
  schedule: {
    directory: ['path/to/otherSchedule'],
  },
} as Partial<EggAppConfig>;

测试

app.runSchedule(scheduleName) 由下列机构提供: @eggjs/schedule 仅用于测试目的的插件 .

示例

it('test a schedule task', async () => {
  // get app instance
  await app.runSchedule('clean_cache');
});

问题和建议

请打开一个问题 这里。 。 。 .

许可证

麻省理工学院

贡献者

Contributors

制造的 贡献者-img。 。 。 .

版本与发布记录

@eggjs/schedule 共发布 56 个版本,首次发布于 2024/12/17;过去 12 个月发布了 33 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
6.1.0latest2026/10/071 个月前
6.0.22026/10/061 个月前
6.0.2-rc.1rc2026/10/061 个月前
6.0.2-rc.02026/09/231 个月前
6.0.2-beta.27beta2026/09/201 个月前
6.0.2-beta.262026/08/073 个月前

关于 @eggjs/schedule 的常见问题

@eggjs/schedule 是什么?

用于鸡蛋的调度插件,支持玉米工作.

如何安装 @eggjs/schedule?

在项目目录运行 npm install @eggjs/schedule,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:egg(4.2.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@eggjs/schedule 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@eggjs/schedule 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@eggjs/schedule 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.18.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@eggjs/schedule 可以商用吗?

@eggjs/schedule 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@eggjs/schedule 的下载量有多少?

根据 npm 官方下载统计,@eggjs/schedule 在 2026/10/13 – 2026/11/11 这 30 天内被下载 5,122 次,日均约 171 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@eggjs/schedule 还在维护吗?

最新版本 6.1.0 发布于 2026/10/07(1 个月前);至今共发布 56 个版本,其中过去 12 个月发布了 33 个;首次发布于 2024/12/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。