Add a scheduled job #
On this page
Prompt:
Clear out the expired sign-up links every night, and show me how to tell whether it ran.
Also works:
- "Send the daily summary every morning at six."
- "Check every hour that the app still responds, and keep a record I can read."
For an application with code of its own, new or deployed, add the schedule to its manifest and choose a handler. A new application is created first, as Deploy from your computer says. For a new service from the server-scheduled-job template, start a new hourly heartbeat. The server-scheduled-job template creates the service, job, handler and tests.
A heartbeat needs no saved state: it only needs to log a line, and tzcloud_read_schedules records each run.
Your AI tool declares the schedule, writes its handler, deploys it, and checks one manual run with tzcloud_run_schedule. With one environment, your request for the job covers that proving run on production.
For an application with production alone, use this checklist:
- Declare the schedule, using the hourly heartbeat recipe for a new service or the existing-application steps for code you already have.
- Write the handler for the declared path.
- Deploy the application to production with the submitted declaration.
- Confirm it runs: check a successful manual run and that the timetable is armed.
What your AI tool does #
- Reads the
scheduleskill (read_context, idskill:schedule) and follows it. - Chooses a handler and follows the Schedule handler reference.
- Asks you what the job does and when it runs, and, on an application with two environments, asks before it promotes.
What you need #
- What the job does, and how often or at what time of day it runs. Times are in UTC, with a one-minute minimum step for either size.
- Whether the job must remember anything from one run to the next, such as the last record it handled.
Before your AI starts #
For the AI tool: Check the following before starting.
- A connected, signed-in AI tool (Connect your AI assistant).
- For an application with code of its own, its identifier, from
tzcloud_create_applicationfor a new one ortzcloud_list_applicationsfor one that already deploys, and its manifest (Author the manifest). - Work that fits one run: one HTTP request that ends inside the execution window, 230 seconds by default. Longer work or a queue does not suit a schedule.
Steps #
1. Declare the schedule #
Start a new hourly heartbeat #
This recipe starts a new service from the server-scheduled-job template. For an application with code of its own, new or deployed, use the next subsection.
- Follow Deploy from your computer to create the application with the size the person names. With no size named and nobody to ask, use Shared 0.5 GB with its default sleep setting. Report the size, that nobody was available, its awake-time charge and the option to request Shared 1 GB for more memory or CPU. Keep the connection and credential checks above. Use production alone unless the person asks to try versions on development first.
- Run
turnzero scaffold --template server-scheduled-job, or use the server-scheduled-job example files from a chat without the CLI. If you run the scaffold, skip thetzcloud_create_applicationstep it prints. Use the application you created in step 1. The template already declaresheartbeatat/jobs/heartbeat. Its handler logs one line per run. The CLI chooses a minute within each hour to spread jobs out. - Submit its manifest and deploy to production. Keep the schedule's name and path aligned with the handler.
- With the person's agreement, call
tzcloud_run_scheduleforheartbeatinproduction, with a newrequest_idandwait_seconds: 45. Ifsettledis false, use the returnedtzcloud_read_schedulescall. Confirm a successful run and read its console, as step 4 explains.
A successful manual run proves the job runs. It leaves next_due unchanged. Reading a later timetable run is optional; that run appears with trigger: "schedule". The manual run does not prove that a timetable run has happened.
Add a schedule to an existing application #
Your AI tool reads tzcloud_read_plan_quotas: schedule-minimum-interval is one minute and schedule-count-limit is 25 for either size. It chooses a timetable within those limits. A run's window, the time it has, is a platform setting, the same for every application, so tzcloud_read_plan_quotas has no row for it.
It then adds a schedule entry to the manifest's services list, or a schedule to the entry already there. The entry's schedules list gives each schedule three members:
name, unique, of at most 64 characters, and matching^[a-z][a-z0-9_]*$, sonightly_cleanuppasses andnightly-cleanupis refusedmanifest_invalid;cron, a five-field expression in UTC, from minute to day of week, so0 3 * * *means 03:00 UTC every day;path, the absolute path of the handler in the application.
The path is never the health path, and never under /__account/ or /__router/.
This complete manifest declares nightly_cleanup at 03:17 UTC every day, with a handler that needs no Schedule package. When updating your application, keep its other services, packages and settings.
{
"manifest_version": 1,
"services": [
{
"kind": "schedule",
"schedules": [
{ "name": "nightly_cleanup", "cron": "17 3 * * *", "path": "/jobs/nightly-cleanup" }
]
}
],
"health": "/health",
"region": "usa",
"egress": [],
"audience": { "kind": "public" },
"packages": []
}
Run scheduled work describes the forms a cron accepts.
If the work does not need an exact time, your AI tool can spread jobs across different minutes instead of scheduling every job at the start of the hour. For example, 17 * * * * runs at 17 minutes past each hour in UTC. Your AI tool keeps any time you requested and respects the one-minute minimum interval. The server-scheduled-job template uses the minute the service was created for its hourly heartbeat; that timetable can be changed.
If you named no time of day and the minute is flexible, your AI tool can choose one shortly after the deploy should finish, putting the first next_due within this session. For a request such as "every night", it asks for a UTC time or proposes one for your approval. Keep a fixed timetable unless you ask for step 4's temporary shortest-interval check. That optional check observes a timetable run separately from the handler check with tzcloud_run_schedule, then restores the requested timetable.
Your AI tool submits the whole manifest with tzcloud_submit_manifest. Submitting the manifest starts no run. Each schedule row of the response says in starts_with which deploy or promote starts the schedule. It also gives window_seconds, the seconds a run has. Each row also gives cron_preview, up to three times the cron yields after the submission, in UTC. Your AI tool reads it to check the cron before it deploys.
2. Write the handler #
Use the Schedule handler reference for the four request headers, response status codes, and the private-path check in one place.
Write the handler to meet that reference's request and response contract. Start a deployed run by hand with step 4's tzcloud_run_schedule. A request you send to the deployed handler's path yourself receives 404 scheduled_handler_only before your code runs. Run scheduled work describes the declaration and when it starts in each environment.
If your existing Node app has no dependencies, add a plain node:http handler to its server. Follow A handler without the package. This handler needs no schedule package entry. It checks x-turnzero-cloud-invocation: schedule and returns 404 for other requests. A heartbeat can log the due instant and respond 200.
If your app uses the Schedule package, use its router. It reads the headers, routes each run to its handler and gives the handler a key for the due instant. For a new service, use the scaffold or example files, which already include a handler.
Before the first deploy, your AI tool can try a handler on the Schedule package's router on your machine. The package's test double, createScheduleDouble from @turnzero/schedule/testing, fires a run with the four headers the platform sets (Test with the double).
3. Deploy #
For a supplied-token connection, follow The command's credential and path. Call tzcloud_deploy_command yourself in this session and run its returned line. Supply TURNZERO_CLOUD_MINTED_TOKEN from the tool's secret store for that line, never by writing the token into the command or chat.
A schedule runs only when the environment's serving version was deployed or promoted with the current declaration. After changing the entry, call tzcloud_deploy_command again and run the command it returns where your tool can, or use tzcloud_deploy_files from a chat without a shell (Ways to deploy). The environment works as follows:
- On an application with one environment, the deploy reaches production and starts the schedule there. Nothing is promoted.
- On an application with two environments, the deploy starts the schedule in development. Production starts it at the next
tzcloud_promote, which your AI tool makes only when you ask (Test in development, then promote).
After the deploy, tzcloud_read_schedules shows the schedule's row with deployed: true and its next due time in next_due. With no environment named, it returns production's rows. Before the deploy, the row shows deployed: false, next_due null, and a reason.
For one read of the serving version with each schedule's last_run and next_due, call tzcloud_check_deploy and read last_release.
Every row also shows cron_preview: up to three future times matching the timetable, in UTC. This checks the cron expression; it does not prove a run started or succeeded. Use next_due for the next due time and runs for what actually happened. A halt, an overlapping run or another refusal can prevent a due run from reaching the handler.
4. Confirm it runs #
Before the check, your AI coding tool tells you once which job it will run and in which environment. With one environment, your request for the job covers this one proving run on production. With two environments, the proving run belongs on development.
For any other manual run on production, your AI coding tool asks and waits for your yes unless you already asked for that run. On development it needs no question. On production, with no prior approval and nobody to ask, it stops and reports.
Your AI tool then fires one run with tzcloud_run_schedule, naming the schedule, the environment, and a new request_id. The run reaches the handler as a due run does: the same path, the same four headers, the same window, and no retry. Its trigger is manual, its due instant is the time of the call unless you pass due_at, and it leaves next_due where it stood.
A successful tzcloud_run_schedule run, with or without due_at, proves the job runs. The timetable is armed once its row shows deployed: true and a next_due time. No wait for a timetable run is needed to complete this check.
To check the handler at one instant, pass due_at. It must be an instant in UTC, on a whole minute, at or before the call, that the cron yields, such as this morning's run time. The run is then due at that instant, and it reaches the handler by the same route a scheduled run at that instant would take. It still leaves next_due where it stood.
The call is refused invalid_request for an instant still to come, one the cron does not yield, or one older than the platform keeps run records (30 days by default). Its detail says why.
That instant may be earlier than the schedule's declaration. The check uses the schedule's current cron expression and the bounds above, not its declaration time. The current declaration must still have been deployed to the chosen environment before the run can start. It starts a manual run now, labelled with that earlier due time; it does not prove the timetable ran then or replay a historical version of the handler.
The run gets the same key as the scheduled run at that instant. So a handler that records keys skips it if that scheduled run already came.
A manual run takes the same route a due run takes, through the serving router. So if the environment has stopped while idle, the run wakes it first, as a due run would. The time the wake takes counts in the run's duration_ms and against its window.
Each run reports woke. It is true where the run found the compute stopped at zero, even if the run then failed, and false where the compute was running. It is null where the read failed or a start was already under way. A null means the platform could not tell whether this run woke the application. The run's outcome does not depend on that read; nothing needs doing for the null.
Here, grain means how the environment runs: as a pod on shared compute or as its own container app. On the pod grain, tzcloud_read_status's compute_state describes the current replica. Running means one is ready for a warm start. Idle means none is ready; it may be scaled to zero, halted, starting or crash-looping. Idle alone does not predict a cold start. On the container grain, woke is always null, and compute_state forecasts nothing.
With wait_seconds, a whole number from 1 to 45, the response waits until the run ends, and run then contains its outcome. Where settled is false, the run is still running, not failed, and next is the tzcloud_read_schedules call that waits for it. Without wait_seconds, the response returns at once with the run running and the same next.
For a server, a run that ended inside the wait can include its console in console: the newest 40 lines from the run, within 4,096 bytes, the handler's among them. Where console.more is present, lines were left out or may still be arriving. It gives the tzcloud_read_logs call that reads them. For a serverless application's scheduled function, console.outcome is unavailable and console.lines is empty. Its console.more gives the tzcloud_read_logs call with source: "pool" to read the function's console lines and failures.
A retry of the same request reuses its request_id, and a new run takes a new one. Identifiers are shared across the application's schedules, so never reuse one for a different schedule. A call with a reused identifier returns the earlier run, and the answer names that run's schedule and environment. A response that is not the platform's own, such as a gateway's error page or a closed connection, says nothing about whether the run started. Read tzcloud_read_schedules first, and repeat the call only with the same request_id.
To read the runs, your AI tool calls tzcloud_read_schedules, with wait_seconds while a run is still running. Then tzcloud_read_logs with source: "platform" returns one event for each run's outcome. To read the handler's console lines, use source: "container" for a server or source: "pool" for a serverless application's function. With source: "router", a run the platform ended at its window shows as a window_ended row with kind: "schedule" and the run's schedule and run. Read logs and counters describes the sources.
Seeing a run started by the timetable is optional. Your AI tool checks one only if next_due falls within this session or you ask to see it. For that check, call tzcloud_read_schedules after the row's next_due time. The platform checks for due runs every 30 seconds. A run may start later if it must wake a stopped environment.
Until the run starts, the row can still show that next_due with in_flight null. Read again after the next check. wait_seconds waits for a run already in flight; it does not wait for a future run to start.
Nothing starts the timetable's run early: tzcloud_run_schedule always starts a manual run. The run the timetable started shows trigger: "schedule" in last_run and among runs. A manual run beside it shows trigger: "manual". If the timetable's run is still running when you read, wait_seconds holds the read until it ends.
For this optional check, where the minute is flexible, choose a minute in UTC a few minutes after the deploy should finish, such as for an hourly job. Submit that timetable and deploy once. Keep it as the real timetable.
If the deploy runs late, the platform compares the oldest due time with its late tolerance, five minutes by default. Beyond that tolerance, it writes one missed row whose detail counts the due times passed over. None of those runs is replayed.
If the platform starts a run late but within the tolerance, it runs for the recorded next_due. Any later due times at or before that check are neither run nor recorded. This can affect timetables with intervals shorter than the tolerance. In either case, next_due advances to the first due time after the check.
For this optional check, after next_due, read tzcloud_read_schedules until last_run shows trigger: "schedule" with started_at set. With two environments, name environment: "development" in that read; no promote is needed.
Your AI tool makes a temporary timetable check only if you ask for one. It uses development when it exists; no further question is needed there. On production, it asks for your yes before changing the timetable for this check.
For that requested check on a timetable whose minute is fixed, temporarily use * * * * *, every minute, on either size. Deploy and check the timetable's run as above. Then submit the real timetable and deploy again. The second deploy counts against the day's deploy limit.
5. Keep state between runs #
Do not rely on memory between runs: the process can stop or restart. A heartbeat needs no saved state; tzcloud_read_schedules records each run and tzcloud_read_logs returns its output.
A job that needs something from the last run, such as the due instants it already handled, keeps it in one of two places:
- a JSON file in a declared storage area, written with a conditional put:
If-Matchwith the version read, orIf-None-Match: *for the first write, so one run never silently overwrites another; - the database, where the manifest declares one (Add a database).
Counters are write-only tallies that tzcloud_read_counters totals, never a place to keep state. Keep state between runs shows a package-router handler that claims each run key in storage before attempting a send.
Expected result #
After the successful manual proving run, tzcloud_read_schedules for the environment shows the schedule's row with:
deployed: true,reason: null, andnext_dueset to the next due time;in_flightnull once the run has ended;last_runwithtrigger: "manual", thedueinstant,started_at,ended_at,outcome: "succeeded", the handler'sstatus, andduration_ms;- the same run among
runs, the most recent runs by due time.
tzcloud_read_logs with source: "platform" returns one event for the run. To read the line the handler wrote, use source: "container" for a server or source: "pool" for a serverless application's function. A later run started by the timetable shows the same, with trigger: "schedule". Reading that timetable run is optional.
Refusals #
See the refusals reference for other platform errors.
The deploy's own refusals are in Deploy from your computer, and the manifest's others in Author the manifest.
| Refusal | Status | Cause | Remedy |
|---|---|---|---|
manifest_invalid |
400 | The schedule entry does not match the schema, such as a name with a hyphen; violations lists the failing paths. |
Correct each path and submit the whole manifest again. |
invalid_request |
400 | tzcloud_read_schedules or tzcloud_run_schedule named an environment other than development or production, a wait_seconds outside 1 to 45, or a due_at still to come, outside the cron, or too old; detail names the member. |
Correct the named member and call again. |
no_such_schedule |
404 | The application has no schedule of that name in the environment the call named. | Name a declared schedule, and name the environment when it is not production. |
schedule_interval_below_plan |
409 | The cron's due times fall closer together than the one-minute schedule-minimum-interval; gap gives the shortest gap. |
Choose a cron with gaps of at least one minute. |
schedule_count_over_plan |
409 | The manifest declares more than the schedule-count-limit, 25 schedules for either size. |
Remove schedules to stay within the limit. |
plan_schedule_conflict |
409 | tzcloud_set_app_size found declared schedules that exceed the target size's limits. |
Submit the manifest within those limits, then repeat the size call. |
plan_quantity_unset |
409 | The size has no value set for a schedule limit. Nothing is recorded. | Wait for platform staff to set the value. |
schedule_not_deployed |
409 | tzcloud_run_schedule named an environment with no deploy or promote since the schedule was declared. |
With one environment, deploy to production, then fire again. With two, deploy and fire in development; name it explicitly in tzcloud_run_schedule. Production starts the schedule at the next promote, which your AI tool makes only when you ask. |
environment_not_created |
409 | tzcloud_run_schedule named development on an application with one environment. |
Fire the run in production, or turn development on and deploy there first. |
run_in_flight |
409 | A run of the schedule has not ended yet. A due time that falls during it is skipped, not queued. | Wait until tzcloud_read_schedules shows the run ended, then fire again. |
target_environment_halted |
409 | tzcloud_run_schedule named a halted environment. |
Call tzcloud_halt_environment with resume: true, then fire again. |
account_paused |
429 | The account has used its balance. The router refuses the run before the handler runs; the plane records skipped with account_paused as its detail, and the due time counts nothing. |
Wait until the next UTC month starts. |
Related #
- Schedule handler gives the headers, response status codes, and private-path check. Run scheduled work describes the declaration,
starts_with, and what a halt does. - Schedule describes the package's router, a handler without the package, and a handler that keeps its state in a file.
- The
scheduleskill, which your AI tool reads withread_contextand the idskill:schedule, gives these steps as the rules your AI tool follows. - Read logs and counters reads the platform's events and the handler's lines.
- Store files covers the storage areas and the conditional put.