Four ways to run scheduled jobs from a TypeScript backend, from node-cron in the process to EventBridge Scheduler on AWS and cron jobs declared in code with Encore.

To run cron jobs from a TypeScript or Node.js backend, use node-cron when there is one long-running process, EventBridge Scheduler pointing at a Lambda function or ECS task when the app runs on AWS and the job should run once per tick rather than once per replica, or Encore, a backend framework with built-in infrastructure where a CronJob declared next to the endpoint is scheduled by the Encore platform in deployed cloud environments, not in preview environments and not locally. In-process schedulers are the quickest to start with and the easiest to get wrong once you run more than one replica.
A cron job usually begins as a few lines of node-cron inside the API process, which works for a single instance. It breaks down when the service scales to three replicas and the nightly invoice job runs three times, or a deploy at 02:00 skips the run without a trace.
Package versions looked up on November 19, 2026: encore.dev 1.58.9 and node-cron 4.6.0.
Encore is a backend framework with built-in infrastructure, so a scheduled job is a typed object next to the endpoint it calls, and the same app declares its database and other resources the same way. On deploy, Encore registers the job and the platform calls the endpoint on schedule. The schedule is Encore platform Managed, so there is no scheduler resource, IAM role or worker to create.
Run in your terminal to get started locally.
// sessions/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("sessions");
// sessions/cleanup.ts
import { api } from "encore.dev/api";
import { CronJob } from "encore.dev/cron";
import { SQLDatabase } from "encore.dev/storage/sqldb";
const db = new SQLDatabase("sessions", { migrations: "./migrations" });
// Deletes sessions that expired more than a day ago.
// Safe to run twice: a second run finds nothing left to delete.
export const cleanupSessions = api({}, async (): Promise<{ deleted: number }> => {
const row = await db.queryRow<{ deleted: number }>`
WITH gone AS (
DELETE FROM sessions
WHERE expires_at < NOW() - INTERVAL '24 hours'
RETURNING id
)
SELECT COUNT(*)::int AS deleted FROM gone`;
return { deleted: row?.deleted ?? 0 };
});
const _ = new CronJob("cleanup-sessions", {
title: "Remove expired sessions",
every: "1h",
endpoint: cleanupSessions,
});
-- sessions/migrations/1_create_sessions.up.sql
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX sessions_expires_at_idx ON sessions (expires_at);
every runs the job at a fixed interval starting at midnight UTC, and the cron job docs require the interval to divide 24 hours evenly, so 6h works and 7h does not. For a specific time or weekday, use schedule with a cron expression instead, for example schedule: "0 9 * * 1" for 09:00 UTC on Mondays. The endpoint must take no request parameters, and it should be idempotent, as the docs note a job can be called more than once under some network conditions.
Cron jobs do not run under encore run or in preview environments. To test one locally, call the endpoint from a test run with encore test, which sets up a local Postgres database with your migrations applied, so the cleanup query runs against the real schema. Once deployed to your own AWS or GCP account, the platform calls the endpoint on schedule, and the Encore dashboard lists each run under Cron Jobs.
For a coding agent this keeps a new job to one change: the agent adds the CronJob next to the endpoint, tests the endpoint locally against the real Postgres schema, and the schedule ships with the same pull request.
Best fit: TypeScript teams that want scheduled jobs to live in the codebase, run per schedule tick rather than per replica in deployed cloud environments (not in previews and not locally), and share the database and tracing of the rest of the app.
On AWS without a framework, the usual answer is EventBridge Scheduler, which invokes a target such as a Lambda function or an ECS task on a cron or rate expression. The schedule lives outside the app, so one target is invoked per tick no matter how many API replicas you have. Delivery is at least once: Scheduler retries a failed or timed-out invocation, so a non-idempotent job can run more than once:
EventBridge cron expressions have six fields, with a year at the end and ? in either the day-of-month or day-of-week field, so 0 * * * * from crontab becomes cron(0 * * * ? *). The role in RoleArn needs lambda:InvokeFunction on the target (or ecs:RunTask and iam:PassRole for an ECS task), and the Lambda function needs its own execution role, its database credentials and network access to the database.
The Lambda handler itself is ordinary TypeScript:
// cleanup.ts (Lambda handler, Node.js 22 runtime)
import fs from "node:fs";
import { Client } from "pg";
export const handler = async (event: { scheduledTime?: string }): Promise<{ deleted: number }> => {
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: {
ca: fs.readFileSync("certs/rds-global-bundle.pem", "utf8"),
rejectUnauthorized: true,
},
});
await client.connect();
try {
const tick = event.scheduledTime;
if (!tick) throw new Error("scheduledTime is required");
const claimed = await client.query(
"INSERT INTO job_runs (job, tick) VALUES ('cleanup-sessions', $1) ON CONFLICT DO NOTHING RETURNING tick",
[tick],
);
if ((claimed.rowCount ?? 0) === 0) {
return { deleted: 0 };
}
const res = await client.query(
"DELETE FROM sessions WHERE expires_at < NOW() - INTERVAL '24 hours'",
);
return { deleted: res.rowCount ?? 0 };
} finally {
await client.end();
}
};
Before enabling the schedule, create the claim table with a unique key for each job and tick:
CREATE TABLE job_runs (
job TEXT NOT NULL,
tick TIMESTAMPTZ NOT NULL,
PRIMARY KEY (job, tick)
);
The create-schedule target above templates <aws.scheduler.scheduled-time> into scheduledTime. The handler claims that tick in job_runs before deleting rows, so a retry of the same tick does no further work. Keep sslmode out of DATABASE_URL when you pass an ssl object, and ship the RDS global certificate bundle with the function. The schedule, the function, both roles and the database secret belong in Terraform or CDK so every environment gets the same setup, and none of it runs on a laptop without a dev account or the SAM CLI. For jobs longer than Lambda's 15-minute limit, target an ECS task instead. More on this route in cron jobs on AWS without Terraform.
Best fit: apps already on AWS whose infrastructure lives in Terraform or CDK, with a few jobs that should run outside the API process.
node-cron runs a schedule inside your Node.js process, which is enough for one long-running instance, such as a small app on a single VM:
import cron from "node-cron";
import { cleanupExpiredSessions } from "./sessions";
cron.schedule(
"0 * * * *",
async () => {
await cleanupExpiredSessions();
},
{ timezone: "UTC", noOverlap: true },
);
noOverlap skips a tick while the previous run is still going, and timezone pins the schedule so a server in another zone does not shift it. Every process that runs this code runs the job, though, so behind a load balancer with three replicas you get three cleanups. Guard it with a Postgres advisory lock (SELECT pg_try_advisory_lock(42) at the start, and skip the run if it returns false), or move it to a single worker. If the process is down at the scheduled minute, the run is skipped, with nothing that records it.
Best fit: a single long-running Node.js process where a missed run is acceptable.
A crontab line on a VM, such as 0 * * * * cd /srv/app && node dist/jobs/cleanup.js, is the oldest option and still fine for one server you manage. It runs outside your app's logging and tracing, needs the same environment variables as the app, and disappears when the VM is replaced, so it fits apps that already live on one host.
Whichever you choose, make each job idempotent and log what it did, not only that it ran. The cron job docs cover cron expressions and the full CronJob options.
For a single long-running process, install node-cron and call cron.schedule('0 3 * * *', handler, { timezone: 'UTC', noOverlap: true }). It runs in the same process, so it stops when the process stops and runs once per replica if you scale out. On AWS, a schedule that should run once per tick, rather than once per replica, usually lives outside the app, in EventBridge Scheduler, or in a framework that manages the schedule for you. EventBridge Scheduler delivers at least once, so the handler should be idempotent.
Create an EventBridge Scheduler schedule with a cron or rate expression and point it at a Lambda function or an ECS task, with an IAM role that lets the scheduler invoke the target. With Encore, you declare a CronJob in TypeScript instead, and the schedule is Encore platform Managed, calling your endpoint in deployed environments (not locally or in previews) with no scheduler resource in your account.
No. Each process that calls cron.schedule runs the job, so three replicas run it three times. Use a lock (for example a Postgres advisory lock), a single dedicated worker, or a scheduler outside the app.
Build TypeScript backends without the infrastructure boilerplate
Encore gives you type-safe APIs, local Postgres and Pub/Sub out of the box, built-in distributed tracing, and automated deploys to your own AWS or GCP account.