# Server-side schedules

> Run a handler on a cron expression or a fixed period, managed by cairnflow.

Source: https://cairnflow.dev/docs/develop/schedules

A schedule invokes a handler on a cron expression or every N milliseconds. Cairnflow stores the
schedule and fires it; your service does not need a timer process or a cron host.

```ts title="setup.ts"

const c = connect({ url: process.env.CAIRN_URL!, apiKey: process.env.CAIRN_KEY! });

await c.schedules.put("nightly-report", {
  cron: "0 2 * * *",
  timeZone: "Europe/Berlin",
  target: { service: "Report", handler: "build" },
  input: { full: true },
});
```

`put` creates or updates. Calling it again with the same definition is a no-op that does not move
the next tick, so it is safe to call on every application start.

## Definition

Exactly one of `cron` or `everyMs` is required.

| Field | Meaning |
|---|---|
| `cron` | Five fields: minute, hour, day of month, month, day of week. Supports `*`, `,`, `-`, `/` and month and weekday names. Day of month and day of week combine with OR. No seconds field, no `L`, `W` or `#` |
| `timeZone` | IANA time zone for `cron`, default `UTC` |
| `everyMs` | Fixed period in ms, aligned to the Unix epoch. Must be at least the server's minimum period (10 seconds unless your operator changed it) |
| `target` | `{ service, handler }`, plus `key` for a virtual object |
| `input` | JSON input for each run, at most 64 KiB encoded. Absent: no input |
| `overlap` | `"skip"`: if the previous run has not finished, skip this tick (default for targets without a key). `"allow"`: always fire (the only option for keyed or scoped targets) |
| `paused` | Create the schedule paused |
| `jitterMs` | Spread the fire time by a deterministic offset below this value, kept before the next tick |
| `limitKey` | Limit key passed to each run |

Schedule names are 1 to 128 characters from `[A-Za-z0-9._-]`, unique within the environment (and
scope).

## Managing schedules

```ts
await c.schedules.pause("nightly-report");   // no ticks until resumed
await c.schedules.resume("nightly-report");  // next tick counted from now, no catch-up
const run = await c.schedules.trigger("nightly-report"); // fire once now
await run.attach();
const s = await c.schedules.get("nightly-report");      // undefined if it does not exist
const all = await c.schedules.list();
await c.schedules.delete("nightly-report");  // false if it did not exist
```

- **`trigger`** fires once immediately, ignoring `paused` and `overlap`, and does not move the next
  tick. It returns an invocation handle. Pass `{ idempotencyKey }` to make retries safe: the same key
  gives the same run. Without one, the client generates a key and keeps it across its own retries.
- **`resume`** computes the next tick from the current time. Ticks missed while paused are not
  fired.
- **`delete`** removes the schedule. Runs it already started are not affected.
- **Changing a definition** with `put` recomputes the next tick from the current time.
- Every method takes an optional `{ scope }` for schedules inside a [scope](/docs/develop/calls#scopes).

`get` returns the definition plus:

| Field | Meaning |
|---|---|
| `nextAt` | Next nominal tick (ms), `null` while paused |
| `fireAt` | When `nextAt` will actually fire, after jitter |
| `upcoming` | The next 10 ticks |
| `last` | Up to 10 recent ticks, newest last: `at`, `id` of the run, `outcome` (`fired` or `skipped`), and sometimes the run's `status` |
| `fired`, `missed`, `skipped` | Counters |

`list` returns `{ schedules, partial, missing, missingRanges }`; `partial: true` means some part of
the environment could not be read and the list may be incomplete.

Managing schedules needs a key that can invoke handlers. The same operations exist over HTTP under
`/schedules/{name}` — see the [HTTP API reference](/docs/reference/http-api).

## Inside the handler

`ctx.schedule` tells a run which tick it belongs to:

```ts
const report = service("Report", {
  async build(ctx, input: { full: boolean }) {
    const tick = ctx.schedule; // { name, at } or undefined
    const day = tick ? new Date(tick.at).toISOString().slice(0, 10) : "manual";
    return ctx.run(`build ${day}`, () => buildReport(day, input.full));
  },
});
```

- `at` is the nominal tick time in ms (for `trigger`, the time it was triggered), not the moment the
  run actually started. Use it as the business date of the run.
- `ctx.schedule` is `undefined` when the handler was invoked any other way.

## Missed ticks

If cairnflow could not fire for a while (for example, a node was down across several ticks), the
schedule fires **once**, for the most recent missed tick. The others are counted in `missed`, not
replayed. Make runs that must cover a period read their range from `ctx.schedule.at` and catch up
on their own if needed.

## Daylight saving time

Cron times are taken literally in the schedule's time zone:

- A local time that does not exist (clocks jump forward) does **not** fire.
- A local time that happens twice (clocks fall back) fires **twice**.

Use `timeZone: "UTC"` (the default) for jobs that must run exactly once a day, or avoid local times
between 1:00 and 3:00.

## Costs and limits

- Each tick is at least one durable write, so very short periods add up. Prefer minutes to seconds.
- Your environment may cap the number of schedules; creating one more fails with `409`. On
  Cairnflow Cloud, see [Beta limits](/docs/cloud/limits).
