Skip to content

Documentation navigation

Scheduling

Cron, interval, and at-time schedules with retry, jitter, and process-wide job registry helpers.

#Scheduling and durable triggers

Agent and Swarm expose cron(), interval() and at() builders. cron() and interval() default to mode="remote", which creates a durable server-side trigger. mode="local" opts into the in-process scheduler. at() is always local. The Scheduled Invocation guide explains the behavior behind these calls.

#Builder signatures

Python
scope.cron(expression, *, tz=None, mode="remote", **options)
scope.interval(interval, *, mode="remote", **options)
scope.at(when, **options)
Callmode="remote" returnsmode="local" returns
cron(...), interval(...)TriggerInvocationBuilderCronInvocationBuilder
at(...)not availableCronInvocationBuilder

tz is a timezone name or datetime.timezone. Remote mode accepts only UTC or an IANA zone name. interval takes a timedelta, and remote intervals must be whole seconds.

**options is name, jitter, misfire, max_overlap, overlap_policy, start_at, end_at, max_runs, retry and emit_events. Remote mode accepts only name and jitter, and anything else raises ValueError. Remote jitter defaults to 60 seconds, applied as a fixed per-trigger offset. See remote schedule rules.

#Remote mode (default)

A durable registration needs a stable key and an immutable deployed-agent target before invoke() registers it:

Python
from maivn import Agent

agent = Agent(name="daily-briefing", api_key="...")
trigger = (
    agent.cron("0 9 * * MON-FRI", tz="America/Chicago")
    .key("daily-briefing")
    .named("Daily briefing")
    .target("agent-123", version=4)
    .with_options(max_attempts=3, backoff="exponential")
    .invoke("Compose the daily operations briefing")
)

print(trigger.scenario_id, trigger.trigger_id, trigger.status)

TriggerInvocationBuilder methods, all of which return the builder:

MethodPurpose
key(value)Stable registration key. Required to register.
named(value)Display name. Defaults to the key.
target(agent_id, *, version)Pins the trigger to a deployed agent version. Scope builders already carry their agent's identity.
where(jsonpath)JSONPath admission filter. None clears it.
with_options(...)Sets the guard options. The guide's trigger options table lists each default and limit.
asking(messages)Sets the prompt template without registering.
display_in_app(), to_connection(connection_id)Choose where results go.
to_slack, to_discord, reply_by_email, comment_on_github, to_webhookName a destination by reference.
emit(event_type)Accepted, but the platform does not currently deliver this output.

Terminal and inspection calls:

CallPurpose
invoke(messages=None) / ainvoke(...)Registers or updates the trigger and returns a Trigger.
declaration_payload(messages=None)The exact create body invoke would send. Needs a key and a target.
declaration()What is declared so far. An unfinished declaration is allowed, with null IDs.
sourceThe frozen source model.

An attached Trigger supports history(), replay(), pause(), resume(), delete(), fire() and fire_stream(), plus arm(), timer(), satisfy() and reply() for SLA and reply sources, each with an a-prefixed async version. These methods call the platform. TriggerFireReceipt carries fire_id, trigger_id and session_id.

#What registration and these calls need

There is no separate deployment approval. The platform does not host your agent, so "deployed" means a process you run has announced the target version. A new account is ready once all of these hold:

  1. A project API key. invoke() and the Trigger methods authenticate with the client's project API key, and act in that key's project.
  2. The key's creator has the right role. The platform checks the person who created the key, as they are now. Registering, updating, pause(), resume() and delete() need an owner or admin of the project or its organization. history() needs project membership, and fire() needs run access to the trigger. A member key that lacks the role gets 403; a key outside the project gets 404.
  3. The target version has been announced. Run maivn serve (or agent.serve()) once with the same project, agent ID and version, and wait for Announced. Until a process has announced that version in the project, registration answers 404. Once announced, it stays registrable after the process stops.
  4. A process is serving when fires are due. Schedules and other fires queue while no process serves the version, and run when one claims them. A process counts as stopped 90 seconds after its last heartbeat.

Schedules, manual fires and on_webhook triggers need nothing more. Other event sources also need the platform to enable that source for your project; see trigger sources.

#Local mode

Use local mode only when the process itself should own the scheduler lifetime:

Python
from maivn import Agent

agent = Agent(name="local-briefing", api_key="...")
job = agent.cron("0 9 * * *", mode="local").invoke("Compose the briefing")
job.on_fire(lambda receipt: print(receipt.fired_at))
job.on_error(lambda receipt: print(receipt.error))

Local mode returns a CronInvocationBuilder. Its terminal calls are invoke, stream, batch, ainvoke, astream and abatch, and each returns a started ScheduledJob. It is not durable across process restarts.

CronInvocationBuilder also has fluent setters: with_scope(scope), with_jitter(jitter), with_retry(retry), with_overlap(policy, max_overlap=1), with_misfire(policy), with_window(start_at=None, end_at=None), with_max_runs(n) and with_emit_events(emit=True).

#Local lifetime and one-shot jobs

Local .invoke(...) starts the job immediately. The scheduler uses background threads, so a short script must keep its process alive until shutdown:

Python
import time

try:
    while not job.is_done:
        time.sleep(1)
except KeyboardInterrupt:
    pass
finally:
    job.stop(drain=True, timeout=30)

agent.at(when).invoke(...) is a local one-shot job. Use a timezone-aware datetime, since a naive one is read as UTC. For local retries pass Retry(...). Durable remote retries use the trigger builder's .with_options(...) instead.

#Scheduling types

All of these import from maivn.

NameSummary
ScheduleBase class with next_after(after) and upcoming(count, *, after=None).
CronSchedule(expression, tz=None)Cron evaluated by croniter. Raises ValueError for an invalid expression.
IntervalSchedule(interval, *, start=None, tz=None)Fixed spacing from start, which defaults to now. The interval must be positive.
AtSchedule(when, *, tz=None)One time. next_after returns None once it has passed.
JitterSpec(min, max, distribution, sigma, align_to, skip_if_overruns_next, seed)Bounded offset applied to each fire. min and max default to zero, distribution to 'uniform', and skip_if_overruns_next to True. JitterSpec.symmetric(amount) and JitterSpec.from_value(...) build one from shorthand.
JitterDistribution'uniform', 'normal' or 'triangular'.
Retry(max_attempts=1, backoff='constant', base=5s, factor=2.0, max_delay=10 min, retry_on=(Exception,))Retry inside one fire.
RetryBackoff'constant', 'linear' or 'exponential'.
MisfirePolicy'skip', 'fire_now' or 'coalesce'. The default is 'coalesce'.
OverlapPolicy'skip', 'queue' or 'replace'. The default is 'skip'.
RunRecordThe outcome of one fire. Fields: scheduled_at, fire_id, fired_at, finished_at, jitter_offset, attempt, status, result, error, metadata, and a duration property.
RunStatus'pending', 'running', 'succeeded', 'failed', 'skipped_misfire', 'skipped_jitter', 'skipped_overlap' or 'cancelled'.
ScheduledJobHandle for a local job. See below.
list_jobs()The live local jobs in this process.
stop_all_jobs(*, drain=True, timeout=None)Stops every live local job.

Retry.delay_for_attempt(n) is the wait before attempt n. It is zero for the first attempt, then base for constant backoff, base * (n - 1) for linear, and base * factor ** (n - 2) for exponential, capped at max_delay unless that is None.

BackpressurePolicy, which maivn also exports, belongs to the event bridge and does not affect schedules. See Events.

#ScheduledJob

Properties: id, name, schedule, max_runs, start_at, end_at, is_running, is_paused, is_done, next_run_at, fire_count, success_count, failure_count, skip_count and last_run.

Methods: history(*, limit=None), next_runs(n=5), pause(), resume(), trigger_now(), stop(*, drain=True, timeout=None), and the callback registrars on_fire, on_success, on_error and on_skip.

Callbacks receive the RunRecord. They run on scheduler threads, and an exception inside one is ignored. history() keeps the newest 1000 records. fire_count counts every fire, including skipped ones.