# @eggjs/schedule 中文文档

规范地址：https://npmcn.com/package/%40eggjs/schedule/

版本：6\.1\.0
npm 元数据更新时间：2026-10-07T08:24:48.517Z
中文译文更新时间：2026-11-13T09:45:28.458Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40eggjs/schedule
原文对照：https://npmcn.com/package/%40eggjs/schedule/?lang=original
项目主页：https://github.com/eggjs/egg/tree/next/plugins/schedule
源码仓库：https://github.com/eggjs/egg

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：38.7 kB，35 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.18\.0
- 运行依赖：6 个
- peer 依赖：egg 4\.2\.0
- 首次发布：2024-12-17T12:00:39.983Z
- 最新版本发布：2026-10-07T08:24:48.081Z
- 近 30 天下载量：5122（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：56（近 12 个月 33 个）

## 中文简介

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

## 安装

```sh
npm install @eggjs/schedule
```

也可以使用：`pnpm add @eggjs/schedule`、`yarn add @eggjs/schedule`、`bun add @eggjs/schedule`

## README

# @eggjs/ 计划

[![NPM version](https://img.shields.io/npm/v/@eggjs/schedule.svg?style=flat-square)](https://npmjs.org/package/@eggjs/schedule) [![Known Vulnerabilities](https://snyk.io/test/npm/@eggjs/schedule/badge.svg?style=flat-square)](https://snyk.io/test/npm/@eggjs/schedule) [![npm download](https://img.shields.io/npm/dm/@eggjs/schedule.svg?style=flat-square)](https://npmjs.org/package/@eggjs/schedule) [![Node.js Version](https://img.shields.io/node/v/@eggjs/schedule.svg?style=flat)](https://nodejs.org/en/download/)

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

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

## 使用量

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

```ts
// {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();
  }
}
```

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

```ts
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` 可以是生成器函数或合成函数。 例如:

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

export default class LoggerExample extends Subscription {
  async subscribe() {
    this.ctx.logger.info('Info about your task');
  }
}
```

```ts
// 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 }`。 。 。 .

### 重排时序

使用 [剪贴板](https://github.com/harrisiirak/cron-parser)。 。 。 .

> 说明: `cron-parser` 支助 `second` 作为不为 linux crontab 支持的可选.
> 
> `@hourly / @daily / @weekly / @monthly / @yearly` 也得到支持.

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

示例

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

### 中间样式排程

用于 `setInterval`,并提供支持 [分钟](https://www.npmjs.com/package/ms) 转换样式

示例

```ts
// 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)`。 。 。 .

```ts
// {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);
};
```

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

```ts
// {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();
  }
}
```

## 动态时间表

```ts
// {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` 规定 [配置、 海关](https://github.com/eggjs/schedule/blob/master/src/config/config.default.ts)。 。 。 .

```ts
// 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>;
```

### 自定义目录

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

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

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

## 测试

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

示例

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

## 问题和建议

请打开一个问题 [这里](https://github.com/eggjs/egg/issues)。 。 。 .

## 许可证

[麻省理工学院](https://npmcn.com/package/%40eggjs/schedule/LICENSE)

## 贡献者

[![Contributors](https://contrib.rocks/image?repo=eggjs/egg)](https://github.com/eggjs/egg/graphs/contributors)

制造的 [贡献者-img](https://contrib.rocks/)。 。 。 .

## 常见问题

### @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 和提交记录判断。

