跳至主要內容

排程

新增於: @mastra/core@1.50.0

beta

此功能目前為 beta 版本。在 API 穩定之前,即使主版本號沒有提升,也可能會有破壞性變更。

排程會按 cron 週期運行 Agent。每次觸發時,Mastra 都會向 Agent 傳送提示:可以透過訊號送進對話串,亦可以在沒有對話串的情況下運行 agent.generate()。排程適合處理重複執行的 Agent 工作,例如每日摘要、定期檢查,或按時在對話中作出提示。

排程會持久儲存,因此重新啟動及重新部署後仍然保留。請在運行期間透過 mastra.schedules 管理排程;這是建立、讀取、更新及刪除(CRUD)排程的標準介面。同一介面亦可管理 Workflow 排程(如要排程 Workflow,請傳入 workflowId 而非 agentId)。

備註

排程需要一個實作了 schedules domain 的儲存空間 adapter。支援的 adapter 及 API 行為請參閱 mastra.schedules 參考資料

快速開始
快速開始 的直接連結

以下排程每小時運行一次 pinger Agent。它不設對話串,因此每次觸發都是一次獨立的 agent.generate() 運行。

src/mastra/schedules.ts
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.',
})

首次建立排程時,Mastra 會啟動排程器,然後按你指定的 cron 時間觸發 Agent。

週期
週期 的直接連結

排程按照 cron 表達式觸發。cron 欄位接受標準的 5、6 或 7 部分 cron 表達式,並會在建立或更新排程時驗證。

你亦可以使用 croner 暱稱,例如 @hourly@daily@weekly@monthly@midnight。如要指定星期與時間的組合,請直接填寫 cron 欄位:

// 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),觸發時間便不會取決於主機的地區設定。如省略此項,cron 會按主機的本地時區解析。

如想以較易閱讀的方式建立 cron,可以使用 cron-time-generator 等使用者端 builder,並將其輸出傳給 cron

無對話串及有對話串的排程
無對話串及有對話串的排程 的直接連結

Agent 排程會以兩種模式之一觸發,採用哪種模式取決於你有否傳入 threadId

無對話串
無對話串 的直接連結

沒有 threadId 時,每次觸發都是一次獨立的 agent.generate() 運行,不會有任何內容寫入對話串。這是最簡單的模式,適合狀態檢查、報告,以及其他不需要對話情境的工作。

有對話串
有對話串 的直接連結

傳入 threadId 後,排程會向該對話串傳送訊號,讓提示加入 Agent 的對話。使用這類排程時,必須同時提供 resourceIdthreadId

src/mastra/schedules.ts
await mastra.schedules.create({
agentId: 'pinger',
cron: '0 9 * * *',
prompt: 'Summarize anything new since yesterday.',
threadId: 'thread-123',
resourceId: 'user-456',
})

有對話串的排程接受額外欄位,用於控制訊號的行為,包括訊號類型、XML 標籤、標籤屬性,以及對話串活躍或閒置時的傳送方式。這些欄位與 agent.sendSignal() 接受的選項一致,並可序列化為 JSON,以便隨排程持久儲存。

這些欄位需要 threadId。完整的有對話串輸入格式請參閱 Agent 排程輸入參考資料

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 <check-in>…</check-in>
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 都會合併至訊號 payload,並同時套用於有對話串和無對話串的排程。

管理排程
管理排程 的直接連結

所有排程操作都使用 mastra.schedules。此服務可以建立、讀取、更新、暫停、恢復、手動運行及刪除排程。

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

pauseresume 的效果會持久保留。run 會即時觸發排程一次,而不影響其原有週期。完整方法清單、篩選條件及 patch 欄位請參閱 mastra.schedules 參考資料

Workflow 排程
Workflow 排程 的直接連結

同一服務亦可建立運行 Workflow 而非 Agent 的排程。請傳入 workflowId 及 Workflow 格式的欄位:

await mastra.schedules.create({
workflowId: 'daily-report',
cron: '0 9 * * *',
inputData: { userId: 'system' },
})

以此方式建立的 Workflow 排程,與 createWorkflow 上宣告式的 schedule 欄位互相獨立。宣告式寫法及 Studio 檢視方式請參閱已排程的 Workflow

自訂 ID
自訂 ID 的直接連結

如果日後需要用可預測的識別碼查找、更新或刪除排程,請傳入 id

await mastra.schedules.create({
id: 'nightly-summary',
agentId: 'pinger',
cron: '0 9 * * *',
prompt: 'Summarize anything new since yesterday.',
})

ID 標準化規則及重複 ID 的處理方式,請參閱 create(input) 參考資料

從 client 操作
從 client 操作 的直接連結

你亦可以透過 /api/schedules 路由,從 @mastra/client-js 使用相同操作,因此可在另一個 process 或 UI 管理排程。client 方法清單請參閱 client-js Agent 排程參考資料

生命週期 hook
生命週期 hook 的直接連結

Hook 讓你在 Agent 排程生命週期的關鍵時間點運行程式碼,例如計算觸發時的參數,或因應結果採取動作。請在 Mastra constructor 的 schedules 下設定。這些 hook 是一組扁平配置,會為每個 Agent 的排程運行;每個 hook context 都包含被觸發的 agentId,如需按 Agent 設定不同的行為,可據此分支處理。Hook 位於 Mastra 層級,因此同時適用於以程式碼定義及已儲存的 Agent。

src/mastra/index.ts
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:在觸發前運行。傳回 object 可覆蓋 promptthreadId 等觸發時參數;傳回 null 可略過該次觸發;傳回 undefined 則使用已儲存的預設值。
  • onFinish:每次觸發到達非錯誤、非中止的終止狀態時運行一次。
  • onErrorprepare 或訊號失敗後運行;Agent 運行失敗時亦會運行。
  • onAbort:運行在串流期間中止時執行。

每個 hook context 除了 scheduletrigger,亦包括 agentId(排程所觸發的 Agent)。

Hook 產生的例外會被捕捉並記錄,絕不會令 worker 改道或觸發另一個 hook。