跳至主要內容

排程

新增於: @mastra/core@1.50.0

beta

此功能目前為 beta。在 API 穩定前,即使未提高主要版本,也可能發生破壞性變更。

排程會依 cron 頻率執行 Agent。每次觸發時,Mastra 會將提示詞傳送給 Agent:可作為訊號送入對話串,或執行不含對話串的 agent.generate()。排程適合每日摘要、定期檢查,或在預定時間提醒對話等週期性 Agent 工作。

排程會持久化,因此能承受重新啟動與重新部署。請在執行階段透過 mastra.schedules 管理排程;這是標準的建立、讀取、更新及刪除(CRUD)介面。相同介面也能管理 Workflow 排程(傳入 workflowId 而非 agentId 即可排程 Workflow)。

備註

排程需要實作 schedules 領域的儲存空間配接器。支援的配接器及 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 的對話。包含對話串的排程除了 threadId 之外,也必須提供 resourceId

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 會立即觸發排程一次,而不影響其執行頻率。完整方法清單、篩選條件及修補欄位請參閱 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) 參考

從用戶端操作
「從用戶端操作」的直接連結

相同操作也能透過 /api/schedules 路由從 @mastra/client-js 使用,因此你可以從個別處理程序或 UI 管理排程。用戶端方法清單請參閱 client-js Agent 排程參考

生命週期掛鉤
「生命週期掛鉤」的直接連結

掛鉤可讓你在 Agent 排程生命週期的關鍵時間點執行程式碼,例如計算觸發時參數,或對結果做出反應。請在 Mastra 建構函式的 schedules 下設定。這些掛鉤是單一扁平套件組合,會針對每個 Agent 的排程執行;各掛鉤情境都包含觸發中的 agentId,需要針對不同 Agent 採取不同行為時,請依此分支。掛鉤位於 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
},
},
})

掛鉤包括:

  • prepare:觸發前執行。傳回物件可覆寫 promptthreadId 等觸發時參數;傳回 null 可略過此次觸發;傳回 undefined 則使用已儲存的預設值。
  • onFinish:每次觸發到達非錯誤、非中止的終止狀態時執行一次。
  • onErrorprepare 或訊號失敗後執行;Agent 執行失敗時也會執行。
  • onAbort:執行在串流途中遭中止時執行。

每個掛鉤情境除了 scheduletrigger 外,也包含 agentId(排程所觸發的 Agent)。

掛鉤例外會被攔截並記錄,絕不會將 Worker 改道或觸發其他掛鉤。