Schedules
Added in: @mastra/core@1.50.0
A schedule runs an agent on a cron cadence. On each fire, Mastra sends a prompt either as a signal into a thread or as a threadless agent.generate() run. Use schedules for recurring work such as daily summaries and periodic checks, including scheduled nudges into a conversation.
Schedules are persisted, so they survive restarts and redeploys. Manage them at runtime through mastra.schedules, the canonical create, read, update, and delete (CRUD) surface. The same surface also manages workflow schedules (pass workflowId instead of agentId to schedule a workflow).
Schedules require a storage adapter that implements the schedules domain. See the mastra.schedules reference for supported adapters and API behavior.
Persisting a schedule doesn't guarantee delivery of each occurrence. Publication is best-effort: the scheduler makes up to three publication attempts, but exhausted attempts or a publisher crash can skip an occurrence. Skipped occurrences aren't replayed, while later recurring fires can continue. See Schedule delivery guarantees for failure reporting and manual rerun precautions.
QuickstartDirect link to Quickstart
The following schedule runs the pinger agent every hour. It has no thread, so each fire is an isolated agent.generate() run.
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-6.2-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.',
})
Schedules fire only in a process where Mastra's background workers are running. The server that mastra dev and mastra build generate starts them for you. With a server adapter or your own script, call mastra.startWorkers() yourself, otherwise schedules are saved but never fire. See Start background workers.
CadenceDirect link to Cadence
Schedules fire on a cron expression. The cron field accepts a standard 5-, 6-, or 7-part cron expression, and it's validated when you create or update the schedule.
croner nicknames also work, for example @hourly, @daily, @weekly, @monthly, and @midnight. For day-and-time combinations, write the cron field directly:
// Every weekday at 9am
await mastra.schedules.create({
agentId: 'pinger',
cron: '0 9 * * 1-5',
prompt: 'Start-of-day check.',
})
Set timezone to an IANA timezone, for example America/New_York, so fire times don't depend on the host's locale. When omitted, the cron resolves against the host's local timezone.
For more readable cron construction, you can use a userland builder such as cron-time-generator and pass its output to cron.
Threadless and threaded schedulesDirect link to Threadless and threaded schedules
An agent schedule fires in one of two modes, decided by whether you pass a threadId.
ThreadlessDirect link to Threadless
Without a threadId, each fire is an isolated agent.generate() run. Nothing is written to a conversation thread. This is the simplest mode and suits status checks, reports, and other work that doesn't need conversation context.
ThreadedDirect link to Threaded
With a threadId, the schedule sends a signal into that thread. The prompt joins the agent's conversation. Threaded schedules require a resourceId alongside the threadId.
await mastra.schedules.create({
agentId: 'pinger',
cron: '0 9 * * *',
prompt: 'Summarize anything new since yesterday.',
threadId: 'thread-123',
resourceId: 'user-456',
})
Threaded schedules accept extra fields that control how the signal behaves, including the signal type, XML tag, tag attributes, and active-or-idle delivery behavior. They mirror the options agent.sendSignal() accepts and stay JSON-serializable so they persist with the schedule.
These fields require a threadId. For the full threaded input shape, see the agent schedule input reference.
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 are merged into the signal payload on every fire and apply to both threaded and threadless schedules.
Managing schedulesDirect link to Managing schedules
Use mastra.schedules for all schedule operations. The service can create, read, update, pause, resume, manually run, and delete 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
pause and resume are durable. run fires the schedule once immediately without affecting its cadence. For the complete method list, filters, and patch fields, see the mastra.schedules reference.
Workflow schedulesDirect link to Workflow schedules
The same service creates schedules that run a workflow instead of an agent. Pass workflowId and the workflow-shaped fields:
await mastra.schedules.create({
workflowId: 'daily-report',
cron: '0 9 * * *',
inputData: { userId: 'system' },
})
Workflow schedules created this way are independent of the declarative schedule field on createWorkflow, see scheduled workflows for the declarative form and Studio views.
Custom IDsDirect link to Custom IDs
Pass id when you need a predictable handle to look up, update, or delete later.
await mastra.schedules.create({
id: 'nightly-summary',
agentId: 'pinger',
cron: '0 9 * * *',
prompt: 'Summarize anything new since yesterday.',
})
See the create(input) reference for ID normalization rules and duplicate ID behavior.
From the clientDirect link to From the client
The same operations are available from @mastra/client-js over the /api/schedules routes, so you can manage schedules from a separate process or a UI. See the client-js agent schedules reference for the client method list.
Lifecycle hooksDirect link to Lifecycle hooks
Hooks let you run code at key points in an agent schedule's lifecycle, for example to compute fire-time parameters or react to the outcome. Configure them on the Mastra constructor under schedules. The hooks are a single flat bundle that runs for every agent's schedules; each hook context carries the firing agentId, so branch on it when you need per-agent behavior. Hooks live at the Mastra level so they apply to both code-defined and stored agents.
import { Mastra } from '@mastra/core'
import { LibSQLStore } from '@mastra/libsql'
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. For a threaded schedule, this is the hand-off, not the end of the run
},
onError: async ({ agentId, phase, error }) => {
// Runs when prepare or the signal threw, or a threadless run failed without aborting
},
onAbort: async ({ agentId, runId }) => {
// Runs when a threadless run was aborted
},
},
})
The hooks are:
prepare: runs before the fire. Return an object to override fire-time parameters such aspromptorthreadId,nullto skip the fire, orundefinedto use the stored defaults.onFinish: runs once per trigger that reached a non-error, non-abort outcome. When a threaded schedule starts a new run, it runs withoutcome: 'succeeded'as soon as the run starts, not when it finishes.onError: runs after a failure inprepareor the signal. For a schedule without athreadId, it also runs when the agent run fails with an error that isn't an abort.onAbort: runs when the run of a schedule without athreadIdwas aborted.
For a schedule with a threadId, the worker sends the prompt to the thread and doesn't wait for the run. Errors and aborts after the run starts surface on that thread's run, not through onError or onAbort.
If you need to react to the completed run, use a threadless schedule. For lifecycle state, cleanup, retries, or multiple steps, use a scheduled workflow.
Every hook context includes agentId (the agent the schedule fired for) alongside schedule and trigger.
Hook exceptions are caught and logged. They never re-route the worker or trigger another hook.
Recurring prompts in Mastra CodeDirect link to Recurring prompts in Mastra Code
Mastra Code offers the /schedules command, which attaches a recurring prompt to the current conversation thread. Unlike mastra.schedules, these schedules live only in the Mastra Code process that created them: nothing is written to storage, and each fire is sent to the thread with agent.sendSignal() directly.
Run /schedules to open a menu with Create schedule and one row per schedule on the current thread. Creating a schedule walks through these steps:
- Choose what each fire sends: a Prompt, a Prompt file that's re-read on every fire, or a Script that runs on every fire.
- Enter the prompt text or the file path. Paths resolve from the project root. For a script, you can add a prompt that's sent after the script output.
- Pick a cadence from
1mto1d, or type one such as20mor3h. Minute steps must divide an hour and hour steps must divide a day. - Confirm.
Scripts run from the project root with a 60-second timeout, and their stdout, stderr, and exit code become the prompt. The extra prompt is never passed to the script.
Selecting an existing schedule offers Run now, Pause or Resume, and Delete. Run now fires the schedule once without changing its cadence, works on paused schedules, and is skipped while a fire of the same schedule is still running.
Each fire arrives on the thread as a user-type signal and shows in the transcript as a schedule entry with the schedule's id, cadence, source, and script exit status. If the thread is busy, the running agent receives the prompt as its next input, the same way a message you type mid-run does. If the thread is idle, it wakes and runs. Schedules fire on any thread in the process, not only the one focused in the terminal. After /new, a new schedule binds to the new thread.
Things to know:
- Session scoped. Schedules exist only in the Mastra Code process that created them and stop when it exits. Other Mastra Code processes sharing the same database never see or fire them.
- Clock boundaries.
5mfires at :00, :05, :10 and so on, not five minutes after creation, and1dfires at local midnight. Hour and day cadences follow wall-clock time across daylight saving changes, like cron. A fire missed while the machine slept, or one whose timer runs more than a minute late, is skipped, and the schedule resumes at the next boundary. - Overlapping fires are skipped. If a script is still running when the next boundary arrives, that fire doesn't run.
Agent schedule toolsDirect link to Agent schedule tools
Turning on Experimental schedule tools in /settings (restart required) gives the agent tools that manage the same schedules: schedule_create, schedule_list, schedule_update (pause or delete), schedule_resume, and schedule_run. The tools only see and change schedules on the thread of the run that calls them. Because a schedule can run a script on every fire, schedule_create, schedule_resume, and schedule_run need the same approval as running a shell command unless YOLO mode is on. Schedules the agent creates are marked created by agent in the transcript.
Ticking from outside the processDirect link to Ticking from outside the process
By default the in-process scheduler polls storage on a timer and fires due schedules. A host that serves many tenants from one database, or that runs without a long-lived process, can instead drive ticks itself, for example from a cron job that calls an HTTP route every minute.
Give each tenant a view of the store with forTenant(). A view only reads and writes that tenant's schedules and triggers, so schedule IDs only need to be unique per tenant:
const schedules = await mastra.getStorage()!.getStore('schedules')
const project = schedules!.forTenant('org_1:project_1')
await project.createSchedule(schedule)
On each tick, call runScheduleTick() with the root store. It lists due tenant schedules across every tenant, passes each occurrence to dispatch, and only then advances the schedule:
import { runScheduleTick } from '@mastra/core/workflows'
await runScheduleTick({
store: schedules!,
now: Date.now(),
dispatch: fire => queue.enqueue({ name: fire.runId, payload: fire }),
onError: (error, schedule) =>
logger.error('Schedule dispatch failed', { scheduleId: schedule.id, error }),
})
- Dedupe on
runId.runIdis the same for every attempt at one occurrence. If the process dies afterdispatchbut before the schedule advances, the next tick dispatches the samerunIdagain, sodispatchmust be idempotent on it, for example by naming the queue task after it. - Handle
onError. A failed dispatch leaves the schedule due, so it's retried on the next tick. A dispatch that keeps failing fails on every tick, andonErroris the only place it's reported. - Tenant schedules only.
runScheduleTick()never fires schedules without a tenant. Those belong to the in-process scheduler, so the two never fire the same occurrence. - Claiming one fire. To advance a single schedule you already dispatched yourself, call
claimScheduleFire({ store, schedule, now }). It returns the claimed occurrence, orundefinedif another tick claimed it first.
Tenant views are supported by the in-memory store, @mastra/pg and @mastra/libsql. Other stores throw from forTenant(). Prune trigger history from the root store. A tenant view refuses prune().
RelatedDirect link to Related
mastra.schedules: API reference for creating and managing schedules.- Signals: the delivery mechanism behind threaded schedules.
- Scheduled workflows: declare a cron schedule on a workflow definition.