---
sidebar_position: 2
title: "Module jobs"
question: How does a module run work on a schedule, on an event or on demand?
kind: guide

---

# Module jobs

A **job** is work a module runs on a schedule, when an event happens, or when
someone triggers it. The module declares its jobs and runs them in its own
process, and JetStream schedules the triggers and delivers them. There is no central scheduler, so adding a module needs no
orchestrator restart.

This page is the reference. For task-by-task steps (a schedule, an event, a run
by hand, a chain of jobs), see [Orchestrations](/capabilities/build/orchestrations/overview).

:::note NATS projects
Jobs need NATS, which `abi new project` sets up. A 2.x project moves to it with
[Migrate from 2.x to 3.0](/capabilities/upgrade/migrate-to-3).
:::

## Declare a job

Import from `naas_abi_sdk.jobs`:

```python
from datetime import timedelta
from naas_abi_sdk import BaseModule
from naas_abi_sdk.jobs import Cron, Every, JobContext, job


class ABIModule(BaseModule):
    @job(triggers=(Every("1h"),), timeout=timedelta(minutes=5))
    async def heartbeat(self, ctx: JobContext) -> dict:
        ctx.log("alive")
        return {"ok": True}  # kept on the run record

    @job(triggers=(Cron("0 0 2 * * *", time_zone="Europe/Paris"),), max_attempts=3)
    async def nightly_report(self, ctx: JobContext) -> None:
        if not await self.has_new_data():
            ctx.skip("nothing new")
            return
        ...
```

Handlers are async methods. A module made by `abi new module` already has a
`heartbeat` job, its body in `jobs.py`: start from it.

## Workflows

A **workflow** is a job with a typed input and output whose steps are checkpointed: `@workflow` instead of `@job`, from `naas_abi_sdk.workflows`. It runs on the same runtime (triggers, `max_concurrency`, `timeout`, `max_attempts`, run records, the Jobs tab), and adds an input checked against its schema, stored steps that a retry skips, and child runs on other modules. Each workflow and pipeline class is published as one, `workflow.<slug>` or `pipeline.<slug>`. See [Write a durable workflow](/capabilities/build/workflows/write-a-durable-workflow), [Schedule a workflow](/capabilities/build/workflows/schedule-a-workflow) and [Monitor and cancel a run](/capabilities/build/workflows/monitor-and-cancel-a-run).

## Triggers

| Trigger | Fires |
|---|---|
| `Every("30s")`, `Every(timedelta(hours=1))` | On a fixed interval, at least one second. |
| `Cron("0 30 9 * * mon-fri", time_zone="UTC")` | On a cron schedule: **six fields, seconds first**, or an alias such as `@daily` ([every alias](/capabilities/build/orchestrations/schedule-a-job#or-use-an-alias)). `time_zone` is optional; without it, UTC. |
| `OnEvent(event_type=<IRI>, filter={...})` | When an ABI event of that type happens, optionally filtered on its fields ([event types and filters](/capabilities/build/orchestrations/react-to-an-event)). |
| `OnEvent("<subject>")` | On any message on a NATS subject. |
| Manual | From the System app (**Run now**), from code, or with `POST /api/admin/system/jobs/<module>/<job>/trigger`. |

A job takes up to 16 triggers and these options:

| Option | Default | Meaning |
|---|---|---|
| `max_concurrency` | 1 | Runs at once, across all replicas. The default never overlaps a run with the next. |
| `timeout` | none | After it, `ctx.cancelled` is set and the run ends `TIMED_OUT`. |
| `max_attempts` | 1 | Attempts before the run fails. |

## What a handler gets

A handler receives a `JobContext`:

- `ctx.payload`: what the trigger carried (the JSON of a manual run, the event).
- `ctx.log(message)`: a line on the run's log, shown in the System app.
- `ctx.skip(reason)`: ends the run as `SKIPPED`, for a poll with nothing to do.
- `ctx.cancelled`: an event to check in a long loop; it is set on a timeout or a
  cancel.
- `ctx.run_id`, `ctx.job`, `ctx.attempt`, `ctx.trigger`.

What the handler returns is stored on the run record. An exception fails the
attempt, and the next one starts after a backoff while `max_attempts` allows.

## Run one by hand

The fastest check is the Nexus **System** app: its **Jobs** tab lists every job
of the engine and of the modules that registered, with a **Run now** button that
takes a JSON payload, and the history of each run: status, attempts, logs,
result and error.

From code, a module triggers its own jobs:

```python
run = await self.atrigger_job("nightly_report", {"day": "2026-10-19"},
                              idempotency_key="report-2026-10-19")
```

Use `self.trigger_job(...)` from synchronous code. Both raise `JobsNotHosted`
until the module has started.

## Write handlers that can run twice

Delivery is **at least once**: after a crash, or a lost acknowledgement, a
handler can run again. Make it safe to repeat (write to a key, not append).

- An `idempotency_key` on a manual trigger deduplicates it for two minutes: the
  same key returns the same run.
- A missed cron tick fires once when the broker comes back, not once per tick
  that was missed. A daylight saving change can skip or repeat a tick.
- `OnEvent` is at most once: an event published while nothing hosts the job is
  lost.

Run records stay for 7 days (skipped ones for 1 hour), at most 1,000 per job.
Retries, timeouts, lost runs and shutdown are in
[Remote modules and jobs](/architecture/remote-modules#module-jobs).

## Jobs the engine runs itself

The engine hosts jobs for its own upkeep: dataset compaction and
cleanup, pruning agent memory, and the two migration jobs
(`agent_memory_migrate`, `activity_log_migrate`) you run once when you
[migrate from 2.x](/capabilities/upgrade/migrate-to-3). They show in the same
Jobs tab under the `naas_abi_core.*` modules.
