> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Schedule **加入版本:** `@mastra/core@1.50.0` > **Beta:** 此功能目前处于 beta 阶段。在 API 稳定之前,可能会在不提升 major 版本的情况下发生破坏性变更。 Schedule 按 cron 频率运行 Agent。每次触发时,Mastra 都会向 Agent 发送 prompt:可以作为 [signal](https://mastra.zisheng.pro/docs/long-running-agents/signals) 发送到 thread,也可以作为不含 thread 的 [`agent.generate()`](https://mastra.zisheng.pro/reference/agents/generate) 运行。Schedule 适合摘要日报、定期检查或按计划向对话发送提醒等周期性 Agent 工作。 Schedule 会持久化,因此可在重启和重新部署后继续存在。在运行时通过 [`mastra.schedules`](https://mastra.zisheng.pro/reference/schedules/overview) 管理它们,这是标准的创建、读取、更新和删除(CRUD)接口。该接口也可管理 [Workflow Schedule](https://mastra.zisheng.pro/docs/workflows/scheduled-workflows)(传入 `workflowId` 而不是 `agentId` 即可安排 Workflow)。 > **备注:** Schedule 需要实现 schedules 域的 [Storage](https://mastra.zisheng.pro/docs/storage/overview) adapter。有关支持的 adapter 和 API 行为,请参阅 [`mastra.schedules` Reference](https://mastra.zisheng.pro/reference/schedules/overview)。 ## 快速入门 以下 Schedule 每小时运行一次 `pinger` Agent。它不使用 thread,因此每次触发都是隔离的 `agent.generate()` 运行。 ```typescript import { Mastra } from '@mastra/core' import { Agent } from '@mastra/core/agent' import { LibSQLStore } from '@mastra/libsql' const pinger = new Agent({ id: 'pinger', name: 'Pinger', instructions: 'Report the current system status in one sentence.', model: 'openai/gpt-5.6-sol', }) const mastra = new Mastra({ agents: { pinger }, storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db' }), }) await mastra.schedules.create({ agentId: 'pinger', cron: '0 * * * *', prompt: 'Give me a status update.', }) ``` 第一次创建 Schedule 时,Mastra 会启动 Scheduler,之后按指定 cron 触发 Agent。 ## 运行频率 Schedule 根据 cron 表达式触发。`cron` 字段接受标准的 5 段、6 段或 7 段 cron 表达式,并在创建或更新 Schedule 时进行验证。 也可使用 `croner` 昵称,例如 `@hourly`、`@daily`、`@weekly`、`@monthly` 和 `@midnight`。对于日期与时间组合,请直接编写 cron 字段: ```typescript // Every weekday at 9am await mastra.schedules.create({ agentId: 'pinger', cron: '0 9 * * 1-5', prompt: 'Start-of-day check.', }) ``` 将 `timezone` 设置为 IANA 时区(例如 `America/New_York`),使触发时间不依赖 Host 的 locale。如果省略,cron 会按 Host 的本地时区解析。 如需更易读地构建 cron,可以使用 [`cron-time-generator`](https://www.npmjs.com/package/cron-time-generator) 等用户态 builder,并将其输出传给 `cron`。 ## 无 thread 和有 thread 的 Schedule Agent Schedule 会以两种模式之一触发,具体取决于是否传入 `threadId`。 ### 无 thread 如果没有 `threadId`,每次触发都是隔离的 `agent.generate()` 运行,不会向对话 thread 写入任何内容。这是最简单的模式,适合状态检查、报告和其他不需要对话上下文的工作。 ### 有 thread 如果提供 `threadId`,Schedule 会向该 thread 发送 [signal](https://mastra.zisheng.pro/docs/long-running-agents/signals),让 prompt 加入 Agent 对话。使用 thread 的 Schedule 还必须随 `threadId` 提供 `resourceId`。 ```typescript await mastra.schedules.create({ agentId: 'pinger', cron: '0 9 * * *', prompt: 'Summarize anything new since yesterday.', threadId: 'thread-123', resourceId: 'user-456', }) ``` 使用 thread 的 Schedule 接受额外字段,用于控制 signal 的行为,包括 signal 类型、XML 标签、标签 attribute,以及活跃或空闲时的发送行为。这些字段与 [`agent.sendSignal()`](https://mastra.zisheng.pro/docs/long-running-agents/signals) 接受的选项对应,并保持可进行 JSON 序列化,以便随 Schedule 一同持久化。 这些字段需要 `threadId`。有关有 thread 输入的完整结构,请参阅 [Agent Schedule 输入 Reference](https://mastra.zisheng.pro/reference/schedules/overview)。 ```typescript await mastra.schedules.create({ agentId: 'pinger', cron: '0 9 * * *', prompt: 'Summarize anything new since yesterday.', threadId: 'thread-123', resourceId: 'user-456', tagName: 'check-in', // renders as attributes: { source: 'cron' }, ifActive: { behavior: 'discard' }, // skip if the thread is mid-stream ifIdle: { behavior: 'wake', // wake the agent if the thread is idle streamOptions: { requestContext: { locale: 'en-US' } }, }, }) ``` 每次触发时,`providerOptions` 都会合并到 signal payload 中,并同时应用于有 thread 和无 thread 的 Schedule。 ## 管理 Schedule 所有 Schedule 操作都通过 `mastra.schedules` 完成。该服务可以创建、读取、更新、暂停、恢复、手动运行和删除 Schedule。 ```typescript const schedule = await mastra.schedules.create({ agentId: 'pinger', cron: '0 * * * *', prompt: 'Status check.', }) await mastra.schedules.pause(schedule.id) await mastra.schedules.resume(schedule.id) await mastra.schedules.run(schedule.id) // Fire once now, off-schedule ``` `pause` 和 `resume` 都会持久生效。`run` 会立即触发 Schedule 一次,不影响其运行频率。有关完整方法列表、筛选器和 patch 字段,请参阅 [`mastra.schedules` Reference](https://mastra.zisheng.pro/reference/schedules/overview)。 ### Workflow Schedule 同一服务可以创建运行 Workflow 而非 Agent 的 Schedule。传入 `workflowId` 和适用于 Workflow 的字段: ```typescript await mastra.schedules.create({ workflowId: 'daily-report', cron: '0 9 * * *', inputData: { userId: 'system' }, }) ``` 以这种方式创建的 Workflow Schedule 独立于 `createWorkflow` 上的声明式 `schedule` 字段。有关声明形式和 Studio 视图,请参阅[定时 Workflow](https://mastra.zisheng.pro/docs/workflows/scheduled-workflows)。 ### 自定义 ID 当你需要可预测的句柄,以便日后查找、更新或删除时,请传入 `id`。 ```typescript await mastra.schedules.create({ id: 'nightly-summary', agentId: 'pinger', cron: '0 9 * * *', prompt: 'Summarize anything new since yesterday.', }) ``` 有关 ID 规范化规则和 ID 重复时的行为,请参阅 [`create(input)` Reference](https://mastra.zisheng.pro/reference/schedules/overview)。 ### 从客户端管理 同样的操作也可以通过 `/api/schedules` 路由从 `@mastra/client-js` 使用,因此可以在独立进程或 UI 中管理 Schedule。有关客户端方法列表,请参阅 [client-js Agent Schedule Reference](https://mastra.zisheng.pro/reference/client-js/agents)。 ## 生命周期 hook Hook 允许在 Agent Schedule 生命周期的关键节点运行代码,例如计算触发时参数或响应结果。请在 `Mastra` 构造函数的 `schedules` 下配置。所有 Agent 的 Schedule 都使用同一个扁平 hook bundle;每个 hook 上下文都带有触发的 `agentId`,因此需要按 Agent 设置行为时可据此分支。Hook 位于 `Mastra` 级别,因此同时适用于代码定义和已存储的 Agent。 ```typescript const mastra = new Mastra({ agents: { pinger }, storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db' }), schedules: { prepare: async ({ agentId, schedule, trigger }) => { // Return overrides, null to skip this fire, or undefined for defaults return { prompt: `Status as of ${trigger.firedAt.toISOString()}` } }, onFinish: async ({ agentId, outcome, runId }) => { // Runs on any non-error, non-abort outcome }, onError: async ({ agentId, phase, error }) => { // Runs when prepare, the signal, or the agent run threw }, onAbort: async ({ agentId, runId }) => { // Runs when the run was aborted mid-stream }, }, }) ``` 可用 hook 包括: - `prepare`:在触发前运行。返回对象可覆盖 `prompt` 或 `threadId` 等触发时参数;返回 `null` 可跳过此次触发;返回 `undefined` 则使用存储的默认值。 - `onFinish`:每个到达无错误、未中止终止状态的 trigger 运行一次。 - `onError`:在 `prepare` 或 signal 失败后运行,也会在 Agent 运行失败时运行。 - `onAbort`:在运行于流式传输中途被中止时运行。 每个 hook 上下文都包含 `agentId`(Schedule 为之触发的 Agent),以及 `schedule` 和 `trigger`。 Hook 异常会被捕获并记录,不会重新路由 worker 或触发其他 hook。 ## 相关内容 - [`mastra.schedules`](https://mastra.zisheng.pro/reference/schedules/overview):创建和管理 Schedule 的 API Reference。 - [Signal](https://mastra.zisheng.pro/docs/long-running-agents/signals):有 thread 的 Schedule 所使用的发送机制。 - [定时 Workflow](https://mastra.zisheng.pro/docs/workflows/scheduled-workflows):在 Workflow 定义中声明 cron Schedule。