server-scheduled-job example #
On this page
Deploy a server app with an hourly scheduled job and tests that simulate a scheduled run without deploying the app.
Anyone with the address can read /health and /api/hello. On Turn Zero Cloud, only the platform’s own runs reach /jobs/heartbeat. The job writes a log line and stores no application data.
These files come from the same source as the scaffold command. They are the starter files before the command adds library packages, application settings, and installed dependencies.
Read the complete starter source under File contents, or open a text download under Files. With read_documentation, use the file path from the Files table as section, for example src/server.mjs. To continue the page, use next_offset with the same stamp.
With a shell #
This template downloads Turn Zero library packages. The command needs this computer's token, kept by turnzero login --origin https://dev.turnzero.ai or turnzero authorize --origin https://dev.turnzero.ai, or TURNZERO_CLOUD_MINTED_TOKEN set for this invocation. Without either, it writes nothing, prints the authorization steps, and exits with status 3.
Authorize this computer, or read How the command finds its credential to use an existing token.
With no CLI token, follow From a chat to adapt these files and deploy through a signed-in MCP connection.
Run this in a new project's root:
turnzero scaffold --origin https://dev.turnzero.ai --template server-scheduled-job
Follow the command's next steps. It writes the application in app/, takes the required library packages, installs dependencies, and runs the tests. The turnzero command explains setup and options.
From a chat #
A Cloud tool name without a prefix is its HTTP API name; your MCP connection lists it with tzcloud_ before it. Account tools such as read_rate_card keep their shorter names. The copied AGENTS.md instructions below use the names listed by the MCP connection.
For this example as it stands, follow the calls and checks below. To adapt it, read Deploying from a chat.
The scaffold can bind its manifest to an application with --application <application id>. From a chat, name the application explicitly in submit_manifest and deploy_files. The platform uses the application named in the call and checks an uploaded manifest's optional application ID only for lowercase UUID form. turnzero deploy --origin https://dev.turnzero.ai and turnzero check --origin https://dev.turnzero.ai refuse a folder whose manifest names another application.
Keep the application paths shown in the table. The download URLs end in .txt so a browser reads the code instead of running it; that suffix is not part of the application filename. Each file is also reproduced below for tools reading this page through MCP.
The template manifest starts with an empty packages list. Read each @turnzero/ dependency's library entry and copy its current name and version into that list. Keep the file:lib/… dependencies in package.json. Leave the files under those lib/ paths out of the deploy_files request; Cloud supplies them from the library. Send no placeholder versions or hashes.
The tests import @turnzero/schedule/testing, and src/server.mjs imports @turnzero/schedule. Both come with the Schedule package after sign-in. Before you sign in, start with A handler without the package. Put the job logic in its own module so a node:test test can call it directly.
The source cron uses minute 0. The scaffold command replaces that minute with the current UTC minute. When using these files directly, choose a minute from 0 to 59 for the hourly schedule before submitting the manifest.
For a new application, make these calls in order. Choose the server size with the person first. With nobody available, use shared-0.5gb and report its awake usage charge and the option to request shared-1gb.
- Call
tzcloud_create_applicationwithnameand the chosensize. Keep its returnedapplication.idfor later calls. - Call
tzcloud_read_libraryforentry: "schedule". Copy each entry’snameand currentversioninto the manifest’spackageslist. - Choose a minute from 0 to 59 for
heartbeatin the manifest’s hourly cron. - Call
tzcloud_submit_manifestwithapplicationand the completemanifestobject. - Call
read_rate_cardand explain the expected usage charges before deploying. Follow the manifest answer’s cost guidance. - Call
tzcloud_deploy_fileswithapplication,environment: "production"and the completefileslist ofpathandcontent. Omit library copies underlib/. - If the deploy is still running, call
tzcloud_read_statuswithapplicationandwait_seconds: 45until it ends. Read the outcome; stop if it failed.
Check it works #
Call tzcloud_check_deploy with application. For the other calls below, pass that application ID and environment: "production".
- Call
tzcloud_request_routefor/health; expect 200 with{"ok":true}. Read/api/hello; expect 200 withhello world. - Call
tzcloud_read_schedules. Check thatheartbeatis deployed and has a next due time. - After that time, call
tzcloud_read_logswithsource: "container". Look forschedule heartbeat ran, keyand the run’s key, and check for errors. - Report whether the scheduled run was observed. If its due time has not arrived, say that this check is still pending.
These calls do not run test/job.test.mjs or invoke the job on demand. Ask the person before any manual production call to tzcloud_run_schedule. Tell the person what these checks leave untested and who can read and write, as described above.
Files #
Paths are relative to the application root—the folder containing package.json. deploy_files uses these paths without an app/ prefix.
| Application path | Read source |
|---|---|
.gitignore |
Text |
AGENTS.md |
Text |
manifest.json |
Text |
package.json |
Text |
src/jobs.mjs |
Text |
src/main.mjs |
Text |
src/server.mjs |
Text |
test/job.test.mjs |
Text |
File contents #
.gitignore #
node_modules/
.env
.env.*
AGENTS.md #
# This service runs on Turn Zero Cloud
The service in this folder is hosted on Turn Zero Cloud. It started from the platform's `server-scheduled-job` template: the smallest Node.js service that deploys, with one handler the platform runs on a schedule. This file describes the template the service started from: keep it current as the service changes.
It started with one schedule, `heartbeat`, which runs the handler in `src/jobs.mjs` once an hour through the Schedule package, and the handler prints one line.
## Where the rules are
Your AI coding tool reads Turn Zero Cloud's rules through the `turnzero` MCP server. That connection gives the tool access to the products on your account. Read the current rules there because they change with the platform.
- Where the server is not connected, set up Turn Zero Cloud first: https://dev.turnzero.ai/cloud/getting-started/set-up/
- Before you change or deploy this service, read the server's `deploy` skill, and before you change its schedule, the server's `schedule` skill.
## What you run here
- The tests: `npm test`, in this folder.
- A local run and a deploy: the `deploy` skill gives each step and the line to run, in this order: `tzcloud_submit_manifest`, the local run, `tzcloud_deploy_command`.
- To run the schedule now, call `tzcloud_run_schedule` with `wait_seconds` to wait for the outcome. A completed run's response includes the handler's log lines in `console`. If they were cut short, are still arriving or could not be read, `more` gives you a `tzcloud_read_logs` call with source `container`. If the run has yet to finish, the response points you to `tzcloud_read_schedules`, which lists every run.
manifest.json #
{
"manifest_version": 1,
"services": [
{
"kind": "schedule",
"schedules": [
{
"name": "heartbeat",
"cron": "0 * * * *",
"path": "/jobs/heartbeat"
}
]
}
],
"health": "/health",
"region": "usa",
"egress": [],
"audience": { "kind": "public" },
"packages": []
}
package.json #
{
"name": "server-scheduled-job",
"private": true,
"type": "module",
"scripts": {
"start": "node src/main.mjs",
"test": "node --test"
},
"dependencies": {
"@turnzero/schedule": "file:lib/schedule"
}
}
src/jobs.mjs #
// src/jobs.mjs, the service's scheduled handlers, one for each schedule
// manifest.json declares
//
// manifest.json declares one schedule, heartbeat, due once an hour. The
// minute in its cron is the minute of the hour, in UTC, at which the
// scaffold wrote this service, so that the services written from this
// template are not all due at the same moment. Any minute serves: the cron
// is yours to change, to any timetable the application's schedule limit admits.
//
// A run of the same due time can reach the handler twice. This handler only
// prints a line, which is safe to repeat, so it keeps no record of the runs
// it has handled. A handler whose effect must not repeat records the run's
// key first, in a row of a database or a file in a storage area, and skips
// the effect where the key is recorded already.
//
// On the platform only the platform's own runs reach a handler's path with
// the four headers the router admits a run by. On your machine any caller
// that reaches the service's port can send them, which matters once a
// handler does more than print.
export const jobs = {
// Prints one line, naming the schedule and the run's key, and answers
// nothing, so the router answers 200 with a JSON body naming the run.
heartbeat: (run) => {
console.log(`schedule ${run.schedule} ran, key ${run.key}`);
},
};
src/main.mjs #
// src/main.mjs, the process entry the start script runs
import { createAppServer } from './server.mjs';
const port = Number(process.env.PORT ?? 8080);
createAppServer().listen(port, () => console.log(`listening on ${port}`));
src/server.mjs #
// src/server.mjs
import { readFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { createScheduleRouter, scheduleDeclarations } from '@turnzero/schedule';
import { jobs } from './jobs.mjs';
// The router for the schedules manifest.json declares, each answered by its
// handler in jobs.mjs. It refuses a handler the manifest does not declare
// and a declared schedule with no handler, so a mismatch stops the service
// as it starts, before any run.
export function createJobRouter() {
const manifest = JSON.parse(readFileSync(new URL('../manifest.json', import.meta.url), 'utf8'));
return createScheduleRouter({ schedules: scheduleDeclarations(manifest), handlers: jobs });
}
// A request's abort signal. The deployed runtime attaches its own signal to each
// request, and it aborts at the request's window. A local run has none of its own,
// and Node's request.signal can abort at a normal request end on some Node 24
// releases, so a local run's signal aborts when the response closes unfinished.
function abortSignalOf(request, response) {
const own = Object.hasOwn(request, 'signal') ? request.signal : undefined;
if (own) return own;
const controller = new AbortController();
response.once('close', () => {
if (!response.writableFinished) controller.abort();
});
return controller.signal;
}
export function createAppServer() {
const router = createJobRouter();
return createServer(async (request, response) => {
// End the response when the request is aborted (abortSignalOf, above).
const signal = abortSignalOf(request, response);
signal.addEventListener('abort', () => response.destroy(), { once: true });
// The schedule's path first: the router answers it, and leaves every other path to the routes below.
if (await router.handle(request, response)) return;
const send = (status, type, body) => {
if (response.destroyed) return;
response.writeHead(status, { 'content-type': type });
response.end(body);
};
// A target that does not parse as a URL names no route, so it is answered 404 below.
let pathname = null;
try {
pathname = new URL(request.url, 'http://localhost').pathname;
} catch {}
if (request.method === 'GET' && pathname === '/health') return send(200, 'application/json', JSON.stringify({ ok: true }));
if (request.method === 'GET' && pathname === '/api/hello') return send(200, 'text/plain; charset=utf-8', 'hello world');
send(404, 'application/json', JSON.stringify({ error: 'not_found' }));
});
}
test/job.test.mjs #
// test/job.test.mjs
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { after, before, test } from 'node:test';
import { createScheduleDouble } from '@turnzero/schedule/testing';
import { createAppServer, createJobRouter } from '../src/server.mjs';
// The schedule manifest.json declares, with its path.
const manifest = JSON.parse(readFileSync(new URL('../manifest.json', import.meta.url), 'utf8'));
const [heartbeat] = manifest.services.find((service) => service.kind === 'schedule').schedules;
// The server on a port of this machine, for the file.
let server;
let base;
before(async () => {
server = createAppServer();
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = `http://127.0.0.1:${server.address().port}`;
});
after(async () => {
await new Promise((resolve) => server.close(resolve));
});
test('GET /health returns 200', async () => {
const response = await fetch(`${base}/health`);
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { ok: true });
});
test('GET /api/hello returns the text hello world', async () => {
const response = await fetch(`${base}/api/hello`);
assert.equal(response.status, 200);
assert.equal(response.headers.get('content-type'), 'text/plain; charset=utf-8');
assert.equal(await response.text(), 'hello world');
});
test('the heartbeat schedule, fired through the test double, is answered 200 and prints its line once', async (t) => {
const printed = t.mock.method(console, 'log', () => {});
const due = '2026-01-01T09:00:00.000Z';
const double = createScheduleDouble(createJobRouter(), { now: () => new Date(due) });
const fired = await double.fire('heartbeat');
assert.equal(fired.outcome, 'answered');
assert.equal(fired.status, 200);
const lines = printed.mock.calls.map((call) => call.arguments.join(' '));
assert.deepEqual(lines.filter((line) => line.startsWith('schedule ')), [`schedule heartbeat ran, key heartbeat@${due}`]);
});
test('a POST to the declared path without the platform\'s headers returns 404 scheduled_handler_only', async () => {
const response = await fetch(`${base}${heartbeat.path}`, { method: 'POST' });
assert.equal(response.status, 404);
assert.equal((await response.json()).error, 'scheduled_handler_only');
});