# cron

> Run functions on cron schedules — hosts `cron::on-tick`; each observer of it passes `{ expression }` as args and receives that expression's ticks.

| field | value |
|-------|-------|
| version | 0.22.1 |
| type | binary |
| license | Apache-2.0 |
| repo | https://github.com/iii-hq/workers |
| supported_targets | x86_64-apple-darwin, aarch64-apple-darwin, x86_64-pc-windows-msvc, aarch64-pc-windows-msvc, x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu, x86_64-unknown-linux-musl, armv7-unknown-linux-gnueabihf |
| author | iii |

## installation

```sh
iii call compose::add worker=cron@0.22.1
```

## readme

# cron

Runs functions on cron schedules. A function runs on a schedule when it
observes `cron::on-tick` with a cron expression as args: this worker calls
`cron::on-tick` once per fire of that expression, at the next matching UTC
time, and every observer of the expression receives the tick.

## Install

```bash
iii call compose::add worker=cron
```

`iii call compose::add` resolves the worker and its dependencies, writes
exact declarations to `worker-compose.yaml`, and reconciles the Compose project.

## Quickstart

Register a function and observe `cron::on-tick` with it, passing the schedule
as args:

```typescript
iii.registerFunction('reports::daily', async ({ output: tick }: { output: CronTick }) => {
  // tick: { expression, scheduled_time, actual_time }
  await sendDigest(tick.scheduled_time)
})

const digest = iii.observe(
  { function_id: 'cron::on-tick', args: { expression: '0 0 9 * * Mon-Fri' }, capture: ['output'] },
  'reports::daily',
)
await digest.ready()   // rejected with INVALID_CRON_EXPRESSION for a bad expression
// later: await digest.dispose() stops the schedule
```

The same in Rust:

```rust
use iii_sdk::{errors::Error, register_worker, Capture, InitOptions, RegisterFunction, Source};
use serde_json::{json, Value};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let iii = register_worker("ws://localhost:49134", InitOptions::default());

    iii.register_function(
        "jobs::tick",
        RegisterFunction::new_async(|observed: Value| async move {
            println!("cron fired: {}", observed["output"]);
            Ok::<Value, Error>(json!({ "ok": true }))
        }),
    );

    iii.observe(
        Source::function("cron::on-tick")
            .args(json!({ "expression": "*/5 * * * * *" }))
            .capture([Capture::Output]),
        "jobs::tick",
    );

    tokio::signal::ctrl_c().await?;
    Ok(())
}
```

With `capture: ['output']` the function receives the `Observed` envelope,
whose `output` is the tick:

```json
{
  "expression": "*/5 * * * * *",
  "scheduled_time": "2026-07-03T12:00:00+00:00",
  "actual_time": "2026-07-03T12:00:00.123456789+00:00"
}
```

Without it, the function receives the `Observed` envelope, with the tick as
its `input` and `output` and the observer's id as `observer_id`.

## Functions

| Function | Args | What it is |
|---|---|---|
| `cron::on-tick` | `{ expression }` | One call per fire of a cron expression. Observers observe the tick; each observer receives the ticks of its own expression. |

### `cron::on-tick`

| Arg | Required | Description |
|---|---|---|
| `expression` | yes | Cron expression parsed by the Rust `cron` crate: six fields `sec min hour day month weekday`, and an optional seventh year field. UTC. |

Rejections, through the observer's `ready()`:

| Code | When |
|---|---|
| `INVALID_ARGS` | `expression` is missing or not a string, or another arg is present. |
| `INVALID_CRON_EXPRESSION` | `expression` is empty or does not parse; the message names the expression. |

The event, the function's input and what its observers observe:

| Field | Description |
|---|---|
| `expression` | The expression that fired, exactly as its observers passed it in args. |
| `scheduled_time` | The fire's scheduled time: RFC 3339 in UTC with a `+00:00` offset, whole seconds (`2026-11-01T09:00:00+00:00`). |
| `actual_time` | When the worker fired it: RFC 3339 in UTC with a `+00:00` offset. |

- **Delivery.** The worker runs one job per distinct expression and calls
  `cron::on-tick` once per fire. iii delivers the tick to the observers of
  that expression (matched by `args.expression` and `input.expression`) whose
  filters accept it. The job starts with the expression's first observer and
  stops with its last. Every fire is delivered, even while the target still
  runs the previous one: observe with `max_in_flight: 1` to run one at a
  time, the later fires waiting their turn.
- **Filters** select ticks by `input`, e.g.
  `{ 'input.scheduled_time': { $gte: '2026-11-01T00:00:00+00:00' } }`.
  Filters compare strings by code point, so a time bound is written in the
  form the worker emits: RFC 3339 with `+00:00`.
- **Metadata.** The observer's `metadata` arrives as each delivery's sidecar.
- **Missed fires.** Fires while the worker is stopped, or disconnected from
  the engine, are skipped; there is no catch-up replay.
- **Day of week.** Write it as a name (`Mon` ... `Sun`). Numerically the crate
  counts Sunday as 1, so `0 0 9 * * 1` fires on Sunday, not Monday.
- **Private.** Only this worker calls `cron::on-tick`; a call from another
  worker is refused with `FORBIDDEN`, and the function cannot be an
  observer's target.
- **One host.** `cron::on-tick` has one host per namespace, so each expression
  fires once per scheduled time. Run one instance: a second one is refused the
  function, and one started under the name a live worker holds is refused
  (`WORKER_NAMESPACE_CONFLICT`) and exits. When the instance restarts, the
  engine hands it the observers back.

A target that needs to know which schedule fired reads `observer_id` from the
envelope, or observes with its own target per schedule.

## Configuration

The worker has no settings. The engine passes a worker's `config:` block as
`--config <file>`; this worker does not read it.

## Console page

While the worker is connected it injects a **cron** page into the console
(page `cron`): every agent-owned schedule with its cadence, next UTC run and
fire count, the `cron::on-tick` observers other workers created for their own
functions, and a composer that turns "every weekday at 09:00, summarise open
PRs" into a schedule. The composer and the manual form ask a harness agent to
call `harness::observe` with `{ function_id: 'cron::on-tick', args: {
expression } }`; schedules created there live in a session of their own, so
each routine keeps its own transcript.

## Console observer activity

The worker injects a cron-specific source section into Consoles that support
`host.observerRenderers`. The activity of a `cron::on-tick` observer (added,
fired, retired) shows a plain-language schedule, the exact expression, and
explicit UTC. Expressions that cannot be summarized without hiding cron
semantics keep an honest “custom schedule” label and the raw expression.

The Console retains the surrounding activity, delivery target/result,
lifecycle state and controls, and raw JSON. Disabling or disconnecting this
worker's injected UI falls back to the generic observer view.

For local UI development:

```bash
pnpm --dir cron/ui test
pnpm --dir cron/ui build
# terminal 1
pnpm --dir cron/ui watch
# terminal 2
cd cron && III_CRON_UI_WATCH=1 cargo run
```

The Rust build embeds `cron/page.js` and `cron/styles.css`; production does
not require a separate asset server.

## skills

This version ships 1 skill file for agents, also browsable on the worker page:

- [`SKILL.md`](https://iii.dev/registry/workers/cron?tab=skills&skill=SKILL.md&version=0.22.1)

### SKILL.md

# cron

The `cron` worker runs registered functions on recurring cron expressions. A
schedule is an observer of `cron::on-tick`: the args hold the expression, and
the target is the function that runs on it:
`iii.observe({ function_id: 'cron::on-tick', args: { expression }, capture: ['output'] }, target)`;
the target reads the tick at `payload.output`.

Install it with `iii call compose::add worker=cron`.

The worker runs one job per distinct expression and calls `cron::on-tick`
once per fire, with a tick holding `expression`, `scheduled_time`, and
`actual_time`. Every observer of that expression receives the tick.
`scheduled_time` and `actual_time` let handlers see drift without querying
the scheduler.

The schedule grammar is the Rust `cron` crate dialect: six or seven fields,
`second minute hour day-of-month month day-of-week [year]`. The year field is
optional. The leading field is always seconds, so `0 */5 * * * *` fires every
5 minutes at second 0, while `*/5 * * * * *` fires every 5 seconds.

Write the day of week as a name: `Mon`, `Tue`, `Wed`, `Thu`, `Fri`, `Sat`,
`Sun`. Numerically this dialect counts Sunday as 1, one ahead of the Unix
convention, so `0 0 9 * * 1` fires on Sunday and a `1` written for Monday
fires a day early. Names avoid the whole question.

## When to Use

- A function should run periodically without a separate scheduler process or
  system crontab entry.
- You need recurring cleanup, reporting, maintenance, or batch jobs that should
  fire on UTC cron windows.
- One function should run on several schedules: observe `cron::on-tick` once
  per expression with the same target.
- A scheduled job should skip some fires: add `filters` on the tick's `input`
  to the observer.

## Boundaries

- Never call `cron::on-tick`: it is private to the cron worker, and a call from
  another worker is refused with `FORBIDDEN`. Observe it with one of your own
  functions as the target.
- The worker does not catch up missed runs after downtime. It schedules the
  next upcoming UTC fire from the time it is running.
- Five-field crontab expressions are refused (`INVALID_CRON_EXPRESSION`).
  Include the seconds field.
- `cron::on-tick` has one host per namespace, so each expression fires once
  per scheduled time. Run one instance; a restarted one gets the schedules
  back.
- For data-change or stream-change reactions, use the relevant state, stream,
  queue, or database worker instead; `cron` fires on the clock only.

## Running on a schedule

Observe `cron::on-tick` when a handler should run on a recurring schedule. The
handler runs as a normal function invocation for each fire.

Reach for it when:

- You need recurring execution such as cleanup, reports, or maintenance.
- A schedule should apply only to some fires: filter on the tick, e.g.
  `{ 'input.scheduled_time': { $gte: '2026-11-01T00:00:00+00:00' } }`.
  Filters compare strings by code point: write time bounds as the worker
  emits them, RFC 3339 with `+00:00`.
- One function should be driven by several schedules; observe once per
  expression and branch on the tick's `expression`.

### How to observe

1. Register a handler: `iii.registerFunction('jobs::cleanup-old-data', handler)`.
2. Observe `cron::on-tick` with the expression as args:

```typescript
iii.registerFunction('jobs::cleanup-old-data', async ({ output: tick }: { output: CronTick }) => {
  // tick: { expression, scheduled_time, actual_time }
})

const cleanup = iii.observe(
  {
    function_id: 'cron::on-tick',
    args: { expression: '0 0 2 * * *' },  // sec min hour dom month dow [year]; daily at 02:00:00 UTC.
    capture: ['output'],
  },
  'jobs::cleanup-old-data',
)
await cleanup.ready()
// later: await cleanup.dispose() stops the schedule
```

`args` takes `expression` only; anything else fails `ready()` with
`INVALID_ARGS`, and an expression that does not parse fails it with
`INVALID_CRON_EXPRESSION`. The handler's return value is ignored.

With `capture: ['output']` the handler receives the `Observed` envelope,
whose `output` is the tick:

```json
{
  "expression": "0 0 2 * * *",
  "scheduled_time": "2026-07-03T02:00:00+00:00",
  "actual_time": "2026-07-03T02:00:00.123456789+00:00"
}
```

Without it, the handler receives the `Observed` envelope: the tick is its
`input` and `output`, and `observer_id` names the observer that fired. The
observer's `metadata` arrives as each delivery's metadata sidecar.

An agent schedules through the harness with `harness::observe`:

```json
{ "function_id": "cron::on-tick", "args": { "expression": "0 30 9 * * Mon" }, "label": "Monday standup notes", "once": false }
```

and retires a schedule with `harness::unobserve` and its `observer_id`.

## api reference

```json
{
  "functions": [
    {
      "description": "One call per fire of a cron expression. Observe it with args { expression } (UTC; 6 fields: sec min hour day month weekday, a 7th year field is accepted); every observer of that expression receives { expression, scheduled_time, actual_time } once per fire. Only the cron worker calls it.",
      "metadata": {},
      "name": "cron::on-tick",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "One fire of an expression: the function's input and what its observers observe.",
        "properties": {
          "actual_time": {
            "description": "When the worker fired it: RFC 3339 in UTC with a `+00:00` offset.",
            "type": "string"
          },
          "expression": {
            "description": "The expression that fired, exactly as its observers passed it in args.",
            "type": "string"
          },
          "scheduled_time": {
            "description": "The fire's scheduled time: RFC 3339 in UTC with a `+00:00` offset, whole seconds.",
            "type": "string"
          }
        },
        "required": [
          "actual_time",
          "expression",
          "scheduled_time"
        ],
        "title": "CronTick",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "One fire of an expression: the function's input and what its observers observe.",
        "properties": {
          "actual_time": {
            "description": "When the worker fired it: RFC 3339 in UTC with a `+00:00` offset.",
            "type": "string"
          },
          "expression": {
            "description": "The expression that fired, exactly as its observers passed it in args.",
            "type": "string"
          },
          "scheduled_time": {
            "description": "The fire's scheduled time: RFC 3339 in UTC with a `+00:00` offset, whole seconds.",
            "type": "string"
          }
        },
        "required": [
          "actual_time",
          "expression",
          "scheduled_time"
        ],
        "title": "CronTick",
        "type": "object"
      }
    },
    {
      "description": "Serve the cron worker's injected console UI assets (the target of its ade::ui::asset observers; the console calls it through each asset's observer with {path}).",
      "metadata": {
        "internal": true
      },
      "name": "cron::ui-content",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Input of the content function: the console asks for one asset by path.",
        "properties": {
          "path": {
            "description": "The asset path from the observer's args (e.g. `state/page.js`).",
            "type": "string"
          }
        },
        "required": [
          "path"
        ],
        "title": "UiContentInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Output of the content function.",
        "properties": {
          "content": {
            "description": "The asset source, verbatim.",
            "type": "string"
          },
          "content_type": {
            "description": "MIME type the console should serve the asset with.",
            "type": "string"
          }
        },
        "required": [
          "content",
          "content_type"
        ],
        "title": "UiContentResult",
        "type": "object"
      }
    }
  ]
}
```
