---
title: Schedule
description: Declare recurring handlers, read each delivered run, and use its key to detect repeats in your handler.
slug: /backend-packages/schedule
order: 8
visibility: public
redirects_from: []
---

# Schedule

Schedule lets your application run its own HTTP handlers on a timetable, without a scheduler of its own. You declare each schedule in your application's [manifest](/cloud/concepts/glossary/#manifest). Turn Zero Cloud calls the declared handler once per due time through the [serving router](/cloud/concepts/glossary/#serving-router), records each run's outcome, and lets you read the runs.

The package provides your application's side of that service. It reads the declarations from the manifest, reads each run the platform delivers, and passes the run to its handler. It writes the handler's response and gives the handler a key that identifies the schedule and due time. Your handler uses that key to detect repeats; the package does not remember earlier runs. A handler needs no package: [A handler without the package](#a-handler-without-the-package) shows one on plain `node:http`.

## Use it when

Use Schedule when your application needs work done on a timetable rather than on a request: a reminder sent every fifteen minutes, a report built nightly, or stale rows removed daily. You declare a schedule in the manifest as a name, a five-field cron expression read in UTC, and the absolute path of a handler on your application's own server. [Author the manifest](/cloud/guides/author-the-manifest/) explains the declaration and its limits: 25 schedules per application and a one-minute floor.

The declaration is one entry of the manifest's `services` list, of the kind `schedule`, whose `schedules` array holds one object per handler with its `name`, `cron`, and `path`. This entry runs one handler at 06:00 UTC every day. A test validates the sample below against the manifest schema.

```json
{
  "kind": "schedule",
  "schedules": [
    { "name": "daily_report", "cron": "0 6 * * *", "path": "/jobs/daily-report" }
  ]
}
```

Do not use it for work that must run a set time after a request, for a queue, or for a task that runs longer than the schedule [execution window](/cloud/concepts/glossary/#execution-window-and-grace-interval). A [scheduled run](/cloud/concepts/glossary/#scheduled-run-and-due-instant) is one HTTP request that must finish inside that window. The window is 230 seconds by default. The actions `read_schedules` and `submit_manifest` return its length in seconds as `window_seconds`.

The window is longer than an ordinary request's, since a scheduled run has no client waiting. It stays below the 240-second limit of the platform's HTTP entry point, through which the run reaches your handler. So a run that runs long ends with the router's `window_ended`, never a dropped connection.

## What it provides

- **Reading a scheduled run.** The function `readScheduledRun(headers)` reads the four headers the [handler reference](/cloud/reference/schedule-handler/#request-headers) lists, which only the serving router sets, into one run value.
- **Reading the declarations.** The function `scheduleDeclarations(manifest)` reads the manifest's schedules, so your handlers are checked against the same text you submit.
- **A router**, `createScheduleRouter`, that handles requests on each declared path, passes each run to its handler, writes the handler's response, and records the run. [The router](#the-router) describes it.
- **The idempotency key.** A manual run can repeat a scheduled due instant when `run_schedule` names it in `due_at`. Both runs have the same `run.key`: the schedule name and due instant. Without `due_at`, a manual run is due at the instant of the call and has its own key. The platform retries nothing. Where a handler's effect must not repeat, record the key in your database or storage first, and skip the action if it is already recorded. A value kept in memory does not count: the process keeps nothing past its end.
- **A [test double](/cloud/concepts/glossary/#test-double)**, `createScheduleDouble` at `@turnzero/schedule/testing`, which fires a declared schedule through the router at once, setting the four headers as the platform does. [Test with the double](#test-with-the-double) shows it in use.

The [Schedule handler reference](/cloud/reference/schedule-handler/) gives the four headers together with the status-code rules, private-path check, and run outcomes.

The platform checks requests to a Node.js HTTP server and permits loopback requests without the [router mark](/cloud/concepts/glossary/#router-mark). It does not apply this check to a separate HTTPS or HTTP/2 server. See [Node.js Runtime](/cloud/backend-packages/nodejs-runtime/).

## Availability

Version 0.3.3 is the package's current version, and this page describes it. Until the library's next publish, `read_library` can return an earlier version, the one you can take, so this page can describe a change that version lacks. The entry includes the `testing` subpath. The entry contains the compiled module, the package's [product statement and detailed contract](/cloud/concepts/glossary/#product-statement-and-detailed-contract), and its integration guide.

Turn Zero Cloud runs the schedule service. It reads the declarations when the manifest is submitted, fires each due time once, and retries no run. The action `read_schedules` returns each run with its trigger, due instant, start, end, outcome, status, duration, and detail. A run still in progress has the outcome `running`. A finished run's outcome is one of `succeeded`, `failed`, `window_ended`, `unreachable`, `skipped`, `missed`, or `abandoned`.

[Run scheduled work](/cloud/guides/author-the-manifest/#run-scheduled-work) says when a declaration starts running, what `starts_with` and `cron_preview` show, the name rules and the schedule limits. It also says how a due run wakes a stopped environment and what a [halt](/cloud/concepts/glossary/#halted-environment) does to schedules. The [Schedule handler reference](/cloud/reference/schedule-handler/) gives the request headers.

## Related feature packages

[Node.js Runtime](/cloud/backend-packages/nodejs-runtime/) closes a declared path to everything but the platform's runs, and enforces the window. [Database](/cloud/backend-packages/database/) and [Storage](/cloud/backend-packages/storage/) are where a handler keeps its idempotency record. [Logging](/cloud/backend-packages/logging/) can receive the router's record of each run beside the application's other entries. [Add a scheduled job](/cloud/guides/add-a-scheduled-job/) adds a schedule and its handler to an application you already have, step by step.

## The router

The package is published in the library as the npm package `@turnzero/schedule`, not on the npm registry; [Use the library](/cloud/guides/use-the-library/#5-install-a-package-s-compiled-code) installs it with one line. The module imports nothing, reads no environment variable, starts no timer, and keeps no state across requests.

### Reading runs and declarations

The platform delivers a run as one `POST` with an empty body to the declared path, with four headers that only the serving router sets. The function `readScheduledRun(headers)` reads them into one run value: the schedule name, the run identifier, the due instant, and a key for that schedule's due instant. It returns no run unless all four headers are present exactly once. Your application never sets the four headers itself.

The run value has `schedule`, `run`, `due` as a `Date`, `dueRaw` as the header gave it, and `key`, the schedule name and the due instant.

The function `scheduleDeclarations(manifest)` reads the `schedules` list of the manifest's `schedule` services entry. It rejects a shape the manifest schema does not allow, so your handlers are checked against the same text you submit. It evaluates no cron expression: the platform does that when the manifest is submitted and computes each due time itself.

### Building and mounting the router

The function `createScheduleRouter({ schedules, handlers })` takes the declarations and one handler per schedule name. At construction it throws on a handler for a schedule the manifest does not declare, a declared schedule with no handler, or two declarations at one path.

Await `router.handle(request, response)` before your application's own routing. It handles requests on declared paths and leaves every other path to your application. A request on a declared path that is not a scheduled run receives 404 `scheduled_handler_only`. A scheduled run reaches its handler with the run value, the request, the response, and the request's abort signal.

The method `router.handle` returns a promise that resolves to `true` after handling the request, or `false` when it leaves the path to your application. Await it before continuing: `if (await router.handle(request, response)) return;`. The properties `router.paths` and `router.schedules` list what it serves. The options also take `record`, a function that receives each run's record in place of standard output, and `now`, the clock.

### The handler's response and the run's record

When a handler returns nothing, the router responds 200 with a JSON body that identifies the run. A handler may return a status and a body, or end the response itself. [Schedule handler](/cloud/reference/schedule-handler/#response-status-and-outcome) says how the status sets the run's outcome. When the handler throws an error, the router responds 500 `handler_failed`.

By default the router writes a JSON line to standard output giving the schedule, the run, the due instant, the path, the status, and the duration. The platform also keeps its own row for the run and a platform event.

### Failures

Before any run, `scheduleDeclarations` and `createScheduleRouter` throw a `ScheduleError` whose `code` gives the fault:

- a manifest the schema does not allow: `manifest_shape`, `schedule_kind_repeated`, `schedules_shape`, `name_shape`, `cron_shape`, `path_shape`, or `duplicate_name`;
- the declarations and the handlers disagreeing: `handler_undeclared`, `schedule_unhandled`, or `path_collision`.

At a request, the router responds 404 `scheduled_handler_only` for a request on a declared path that is not a scheduled run, and 500 `handler_failed` where the handler throws.

## Test with the double

The function `createScheduleDouble(router)` from `@turnzero/schedule/testing` wraps the router your server builds from `manifest.json` and your handlers. Its method `fire(schedule, { due })` delivers one run at once, with the four headers the platform sets, and returns the router's response. The list `fires` records each fire, and `reset()` empties it. The sample fires one due instant twice, the way a run can reach a handler again, and shows the second run sending nothing. A test runs this sample over the double.

```js
import assert from 'node:assert/strict';
import { createScheduleRouter, scheduleDeclarations } from '@turnzero/schedule';
import { createScheduleDouble } from '@turnzero/schedule/testing';

const manifest = {
  manifest_version: 1,
  services: [{ kind: 'schedule', schedules: [{ name: 'daily_report', cron: '0 6 * * *', path: '/jobs/daily-report' }] }],
};
// The keys of the runs already handled: a Set here, a table of your database once deployed.
const handled = new Set();
const router = createScheduleRouter({
  schedules: scheduleDeclarations(manifest),
  handlers: {
    daily_report: (run) => {
      if (handled.has(run.key)) return { body: { sent: false } };
      handled.add(run.key);
      return { body: { sent: true } };
    },
  },
});
const schedule = createScheduleDouble(router);

const due = '2026-10-08T06:00:00.000Z';
const first = await schedule.fire('daily_report', { due });
assert.equal(first.outcome, 'answered');
assert.deepEqual(first.json, { sent: true });
// The same due instant fired again reaches the handler with the same key, and sends nothing.
assert.deepEqual((await schedule.fire('daily_report', { due })).json, { sent: false });
```

The action `run_schedule` fires a run due now, or with `due_at` at a past instant the cron yields, and only on a deployed environment. A run given `due_at` has the key of the scheduled run due then. To replay one due instant before any deploy, fire it twice through the double with `double.fire('<schedule>', { due })`. The second fire has the same `run.key`, so the test shows whether the handler skips an effect it already made. The integration guide in the entry shows this under Testing the composition, in its Test setup section.

The router's own failures, which [Failures](#failures) lists, reach a test through the double as they reach a request. The double throws these codes of its own before it sends anything:

| Refusal | Cause | Remedy |
| --- | --- | --- |
| `schedule_undeclared` | `fire` or `headersFor` named an undeclared schedule. | Fire a name the manifest declares. |
| `run_shape` | The `run` given is empty or contains a comma or whitespace. | Pass a plain token, or omit it. |
| `due_shape` | The `due` given does not parse as an instant. | Pass an ISO 8601 text or a `Date`, or omit it. |
| `scheduled_handler_only` | `request` reached a declared path without the four headers of that path's schedule. | Pass `headersFor(schedule, due)`, or use `fire`. |

## Send a run to your machine

The platform sends scheduled runs only to a deployed copy. A local run, such as `turnzero run --port 3000` or `node --env-file=.env`, receives one only when your tool sends it. Send one `POST` with an empty body and the four headers to the declared path. A local run loads no runtime harness, so nothing there requires the router mark ([Run your app on your computer](/cloud/guides/run-your-application-on-your-machine/#4-know-what-a-local-run-reaches)). For the `daily_report` schedule above, in bash:

```bash
curl -i -X POST \
  -H 'x-turnzero-cloud-invocation: schedule' \
  -H 'x-turnzero-cloud-schedule: daily_report' \
  -H 'x-turnzero-cloud-run: local_1' \
  -H 'x-turnzero-cloud-schedule-due: 2026-10-08T06:00:00.000Z' \
  http://localhost:3000/jobs/daily-report
```

In Windows PowerShell 5.1, type `curl.exe`, as [Windows PowerShell](/cloud/getting-started/prerequisites/#windows-powershell) says, and keep the request on one line:

```powershell
curl.exe -i -X POST -H 'x-turnzero-cloud-invocation: schedule' -H 'x-turnzero-cloud-schedule: daily_report' -H 'x-turnzero-cloud-run: local_1' -H 'x-turnzero-cloud-schedule-due: 2026-10-08T06:00:00.000Z' http://localhost:3000/jobs/daily-report
```

Change the port, the path, and the schedule's name to your own. The due instant keeps the form the [header table](/cloud/reference/schedule-handler/#request-headers) shows. Sent twice with the same due instant, the request reaches the handler with the same `run.key`, as the double's second fire does.

## What an application must do

While the account is paused for its balance, the router refuses a scheduled run `account_paused` before any leg. The plane records it `skipped` with that name as its detail; its due time counts nothing.

Declare every scheduled handler in the manifest, and pass the router a handler for every declaration. Do not pass the router a handler with no declaration: `createScheduleRouter` throws at startup, so the mismatch fails before any run.

Finish each run inside the schedule execution window, and stop the run's work when the request's abort signal fires. The serving router and the runtime harness end a run at the window, and a handler that keeps running past the grace interval ends the process. Start no timer, polling loop, or child process that outlives the response. [Node.js Runtime](/cloud/backend-packages/nodejs-runtime/) describes the window, the signal, and the check on a declared path.

A run still going at the window is recorded `window_ended`, not `failed`. The router ends it at that moment, the request's abort signal fires, and a response the handler sends afterwards has nowhere to go. Nothing retries it: the schedule's next due time is the next run.

Make each handler safe to repeat for the same schedule and due instant, using the key the run includes and the application's own stored state.

Submit the manifest, then deploy, as [Run scheduled work](/cloud/guides/author-the-manifest/#run-scheduled-work) describes for one environment and for two. Read each run through `read_schedules` and its platform event through `read_logs`.

The action `read_schedules` confirms that a schedule is registered, before any run. The schedule's row shows its `cron` and `path`, `deployed: true` once the environment has a deploy made at or after the declaration, and its next due time in `next_due`.

A schedule already firing before a deploy keeps its next due time across it. Only a schedule that awaited the deploy starts from the deploy's instant, at its first due time after it. The exception is a deploy to a [halted](/cloud/concepts/glossary/#halted-environment) development environment, which ends the halt: it starts every past-due schedule of that environment again from the deploy's instant, and nothing is recorded missed.

The platform checks for due runs every 30 seconds, so a run starts within about 30 seconds of its due instant, and later where it wakes a stopped environment. The action `read_schedules` gives each run its `due` and its `started_at`. The wake counts inside the run's `window_seconds`, and `read_schedules` says so in its `detail` for an environment that scales to zero when idle.

An environment whose sleep setting is on stops after 30 idle minutes. Development always sleeps when idle. `read_plan_quotas` returns the interval as each size's `free-idle-stop` row, in seconds. A schedule due less often usually finds the environment asleep. Its run starts the process cold, using part of the same `window_seconds`; the handler has the window less its start-up time, so keep its work well inside it.

A start that uses up the whole window ends the run `window_ended`, on either [grain](/cloud/concepts/glossary/#grain-and-development-group): compute of its own or shared compute. On shared compute, the cluster keeps a waking run waiting for as long as the window. The run is not run again: the next run is at the next due time.

A row with `deployed: false` has `next_due` null, and its `reason` says why: `no_deploy` where the environment has no deploy or promote yet, or `awaiting_deploy` where the declaration is newer than the version serving. After a `roll_back` to a version from before the declaration, the schedule waits that way and does not fire until a later deploy or promote. Its `in_flight` gives the run in progress, and `runs` lists the most recent runs by due time, 5 by default and up to 100 with `limit`. Its `window_seconds` is the number of seconds a run has before the platform ends it.

The `read_schedules` response's `page` is the address of this page, and its `detail` refers to this section. Where a run can start now, the `detail` also points to the step [Confirm it runs](/cloud/guides/add-a-scheduled-job/#4-confirm-it-runs), which fires a run and reads it.

With no environment named, `read_schedules` returns production's schedules. Its `halted` member is `false` while the environment runs. While it is halted, `halted` is `{ at, by }`: when the halt began, and `developer` or `platform`. On an application with production alone, `read_schedules` naming `development` returns no schedules; its `detail` explains why and names `create_environment` to add development.

To fire one run now with `run_schedule` and read how it ended, follow the step [Confirm it runs](/cloud/guides/add-a-scheduled-job/#4-confirm-it-runs); [run_schedule](/cloud/reference/actions/run-schedule/) in the generated reference gives every member of its response, `console` among them.

To read any run's outcome without sleeping, add `wait_seconds`, a whole number from 1 to 45, to `read_schedules`. The read then waits to respond until no run of the environment is in flight, checking every two seconds for at most 45 seconds. Its `settled` member is true where no run was in flight at the time of the response, and `waited_ms` says how long it waited. A value of `settled: false` means a run is still in flight, not that it failed, so read again with `wait_seconds`.

### Keep state between runs

A handler that passes nothing from one run to the next, such as a heartbeat, keeps no state. The action `read_schedules` records each run, and `read_logs` returns the lines the handler writes.

Keep the state a handler needs between runs in a JSON file in a declared [storage](/cloud/backend-packages/storage/) area, or in the database where the manifest declares one. The process keeps nothing past its end. Write the file with a conditional put, so one run never silently overwrites another: `If-Match` with the version you read, or `If-None-Match: *` for the first write. A counter is a write-only tally that `read_counters` totals, never a place to keep state.

A handler reads the platform's origin and its credential from the settings a [deployed copy](/cloud/concepts/glossary/#running-copy) receives: `TURNZERO_CLOUD_GATEWAY_URL`, or `TURNZERO_CLOUD_API` where the platform sets no separate gateway origin, and `TURNZERO_CLOUD_APP_TOKEN`. [A deployed app's settings](/cloud/concepts/the-settings-a-deployed-copy-receives/) lists every setting.

The sample below is a handler for the package's router. It claims each `run.key` in a separate JSON file in the declared `report-state` storage area before sending the report. It skips a key that already has a claim.

```js
const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL ?? process.env.TURNZERO_CLOUD_API;
const claimFile = (key) => `${origin}/storage/v0/areas/report-state/files/claims/${encodeURIComponent(key)}`;
const bearer = { authorization: `Bearer ${process.env.TURNZERO_CLOUD_APP_TOKEN}` };

export async function nightlyReport(run) {
  // Claim this key before attempting to send the report.
  const claim = await fetch(claimFile(run.key), {
    method: 'PUT',
    headers: {
      ...bearer,
      'content-type': 'application/json',
      'x-acting-identity': 'nightly-report',
      'if-none-match': '*',
    },
    body: JSON.stringify({ key: run.key }),
  });
  if (claim.status === 412) return; // Another call has already claimed this key.
  if (!claim.ok) throw new Error(`claim write answered ${claim.status}`);

  // A failure after this claim may leave the report unsent.
  // ... build and send the report ...
}
```

This sample makes at most one send attempt per key while its claim file exists. Each run creates one small JSON file that counts toward stored data and remains until deleted.

A claim may be saved even when its PUT reports an error. Replaying that key then skips the send and can complete successfully. A failure after a successful claim can also leave the report unsent.

To allow another send attempt, delete the matching claim only after checking that repeating the send is safe. A failed run alone does not prove the report was never sent. Deleting a claim removes repeat protection for that key.

If that trade-off is unsuitable, use a sender that can deduplicate `run.key` and keep pending work durably. For an effect confined to your database, save the key and the change in one transaction.

Under the platform credential the calls need no environment header, because the credential fixes the environment. Each environment keeps its own claim records.

To start a new service with a scheduled handler already in place, run the turnzero command's [`scaffold` line](/cloud/concepts/turnzero-command/#the-scheduled-job-template) with `--template scheduled-job`. It writes an hourly heartbeat like the one below, but through this package's router, with its test double and tests.

### A handler without the package

The smallest handler is a heartbeat on a cron schedule, and it needs no package. Its manifest's `packages` list has no `schedule` row. It is an ordinary `POST` route at the declared path that responds 200 at once and keeps no state.

Written without the package's router, it checks for `x-turnzero-cloud-invocation: schedule` itself and responds 404 otherwise. See [Private-path check](/cloud/reference/schedule-handler/#private-path-check) for the checks on a deployed copy. The handler's own check also protects local runs and frameworks routing beyond the declared path.

A second run for the same `x-turnzero-cloud-schedule-due` instant does the same again, so it is safe to repeat. [Confirm a deployed handler](/cloud/guides/add-a-scheduled-job/#4-confirm-it-runs) with `run_schedule`.

```js
import { createServer } from 'node:http';

// The manifest declares a schedule whose handler path is /jobs/heartbeat.
createServer((request, response) => {
  if (request.url === '/jobs/heartbeat') {
    if (request.method !== 'POST' || request.headers['x-turnzero-cloud-invocation'] !== 'schedule') {
      response.writeHead(404).end();
      return;
    }
    console.log(`heartbeat due ${request.headers['x-turnzero-cloud-schedule-due']}`);
    response.writeHead(200).end();
    return;
  }
  // ... the application's own routes, the health path among them ...
}).listen(Number(process.env.PORT));
```
