Back to guides

Guides · April 12, 2026

Postgres cron jobs: pg_cron, scheduled queries, and external triggers (2026)

pg_cron is the scheduler most Postgres hosts already ship, but each one switches it on differently, it lives in one database and one timezone, and its history table never shrinks. Here is the setup host by host, how to keep it healthy, and what to use when you can't install it.
crontap.com / guides
pg_cron on RDS, Aurora, Cloud SQL, AlloyDB, Azure, Neon and self-hosted Postgres: how each enables it, cron.database_name, GMT schedules, job_run_details cleanup, long jobs and locks, plus pg_timetable, crontab and external HTTP cron.

You have a list of things Postgres should do on its own: prune old events every night, refresh a materialized view every hour, create next month's partition before the 1st, run VACUUM ANALYZE on the table autovacuum can't keep up with. Postgres has no scheduler built in, so the first search lands on pg_cron, and the second one is usually "how do I enable pg_cron on RDS" (or Cloud SQL, or Neon), because every host does it a little differently.

This guide covers pg_cron on the hosts people actually run, checked against each provider's docs in November 2026, then the settings that trip people up once it's running: which database the jobs live in, which timezone they fire in, a history table that never shrinks, and slow jobs that queue up behind themselves. It ends with what to use when you can't install pg_cron at all, and when the clock belongs outside the database. If you're on Supabase, the Supabase cron jobs guide covers Supabase Cron, pg_net and Edge Functions in depth.

pg_cron is the scheduler most Postgres hosts already ship

pg_cron is an extension plus a background worker. You give it a name, a cron expression and a SQL command; it stores the job in cron.job, wakes up every minute, and runs whatever is due in its own connection or background worker. The job is plain SQL, so anything you'd type in psql works: a delete, a call to a procedure, refresh materialized view concurrently, or VACUUM.

-- Every night at 03:00: prune events older than 90 days
select cron.schedule(
  'prune-old-events',
  '0 3 * * *',
  $$delete from events where created_at < now() - interval '90 days'$$
);
 
select cron.schedule('refresh-hourly-metrics', '5 * * * *',
  'refresh materialized view concurrently hourly_metrics');
 
select cron.schedule('vacuum-orders', '30 4 * * 0', 'VACUUM ANALYZE orders');

Calling cron.schedule again with the same name replaces the job. cron.alter_job changes one field (pass active := false to pause it), cron.unschedule('prune-old-events') removes it, and select * from cron.job lists everything. The syntax is standard five-field cron with two extras: $ in the day field means the last day of the month, and an interval like '30 seconds' (1 to 59) runs a job more often than once a minute.

GMT

Default timezone

cron.timezone, restart to change

32

Jobs at once

cron.max_running_jobs default; RDS and Cloud SQL ship 5

1-59 s

Shortest interval

'30 seconds' syntax, no other units mixed in

What it doesn't do matters as much. There is no retry: a failed run is a row with status = 'failed', and the job just runs again at its next time. There is no alert either. Everything you know about a run is in cron.job_run_details and the Postgres log, which someone has to read.

Which hosts support pg_cron, and how each one turns it on

As of November 2026, from each provider's own documentation:

Hostpg_cronHow you enable it
Self-hostedYes, PostgreSQL 10+Install the package, shared_preload_libraries, restart
Amazon RDSYes, 12.5+Custom parameter group, reboot, extension in postgres
Aurora PostgreSQLYes, 12.6+Same as RDS
Google Cloud SQLYes, pg_cron 1.6.4Flag cloudsql.enable_pg_cron=on (restarts)
Google AlloyDBYes, pg_cron 1.6.7Flag alloydb.enable_pg_cron=on (restarts)
Azure flexible serverYes, PostgreSQL 11 to 18azure.extensions allow-list plus shared_preload_libraries, restart
NeonYes, PostgreSQL 14+Set cron.database_name through the API, restart the compute
Crunchy BridgeYes, preloadedcreate extension pg_cron, or the dashboard's Scheduler
DigitalOceanStandard Edition onlyListed, setup not documented
SupabaseYes, after you enable the Cron integrationIntegrations > Cron (guide)
Tiger Cloud (Timescale)On requestContact support, or use TimescaleDB's add_job
Heroku Postgres, RenderNoRun the SQL from outside (see below)

Pick your host below and type the database your tables live in. You get the restart and timezone facts for that host, the enable steps, and the files to copy, including a first job scheduled the way that host allows.

pg_cron, host by host

from each provider's docs, Nov 2026

Restart needed
Yes, after the parameter group change
Jobs are managed from
postgres, then schedule_in_database
Timezone
GMT/UTC only
Concurrent jobs
5 jobs by default
  1. 1Edit a custom parameter group

    Add pg_cron to shared_preload_libraries, keeping the libraries already listed. The default group can't be edited.

  2. 2Reboot the instance

    The library only loads at startup.

  3. 3Create the extension in postgres

    Connect to postgres as a user with rds_superuser. The scheduler lives there; schedule_in_database sends jobs to app.

aws rds modify-db-parameter-group \
  --db-parameter-group-name my-pg-params \
  --parameters '[{"ParameterName":"shared_preload_libraries","ParameterValue":"pg_stat_statements,pg_cron","ApplyMethod":"pending-reboot"}]'

aws rds reboot-db-instance --db-instance-identifier my-db
  • Keep max_worker_processes above cron.max_running_jobs: RDS runs jobs as background workers and fails runs when it runs out of them.
  • If rds.allowed_extensions is set on the instance, add pg_cron to it too.
  • Don't grant INSERT or UPDATE on cron.job: AWS warns a user could edit the username column and run jobs as rds_superuser.
Source: docs.aws.amazon.com
Facts, steps and gotchas taken from each provider's pg_cron or extensions documentation in November 2026. Replace my-db, my-rg and similar names with your own.

Self-hosted: install, preload, restart

On your own server, pg_cron is three steps and one restart. The pg_cron README covers PostgreSQL 10 and newer.

  1. 1

    Install the package for your major version

    sudo apt-get -y install postgresql-18-cron   # Debian, Ubuntu
    sudo yum install -y pg_cron_18               # RHEL, Amazon Linux
  2. 2

    Preload it and pick the database

    # postgresql.conf
    shared_preload_libraries = 'pg_cron'   # append to any existing list
    cron.database_name = 'app'             # default: postgres

    Then restart Postgres. cron.database_name, cron.timezone and cron.max_running_jobs are all read at startup, so set them now and save yourself a second restart.

  3. 3

    Create the extension and grant it

    -- connected to app, as a superuser
    create extension pg_cron;
    grant usage on schema cron to app_owner;

    Jobs run as the role that scheduled them, so schedule from the role that owns the tables, not from postgres.

pg_cron lives in one database

The first error most people hit is can only create extension in database postgres. pg_cron keeps its job table in exactly one database per server, named by cron.database_name, and the default is postgres. Your tables are in app. There are two ways out.

Keep the extension in postgres and send jobs elsewhere. cron.schedule_in_database (pg_cron 1.4+) takes the target database as an extra argument. This is the path on RDS and Aurora, where AWS documents the scheduler living in postgres:

-- run this while connected to postgres
select cron.schedule_in_database(
  'prune-old-events',
  '0 3 * * *',
  $$delete from events where created_at < now() - interval '90 days'$$,
  'app'
);

Or move pg_cron into your database. Set cron.database_name = 'app' and create the extension there. Cloud SQL, AlloyDB and Azure expose the setting as a flag or server parameter (restart required), and Neon requires it: you set it through the API before the extension will install, and schedule_in_database isn't supported there at all. When pg_cron and your tables share a database, plain cron.schedule is all you need.

Schedules run in GMT unless your host lets you change it

pg_cron reads every schedule in the timezone set by cron.timezone, and the default is GMT. 0 3 * * * means 03:00 UTC, which is 22:00 the previous evening in New York in winter and 23:00 in summer.

Whether you can change that depends on the host. On self-hosted Postgres, Azure flexible server and AlloyDB, cron.timezone is a setting you can change with a restart. Cloud SQL doesn't list it among its supported flags, AWS doesn't document it for RDS or Aurora, and Neon says plainly that pg_cron interprets every schedule as UTC whatever the setting says.

If you do set a local zone like Europe/Berlin, remember it applies to every job on the server, and that daylight saving time adds two awkward nights a year. Keep fixed-time jobs out of the 01:00 to 03:00 local window, the hours a clock change skips or repeats, and the question of whether a 02:30 job ran twice never comes up. For most teams it's simpler to leave pg_cron in UTC and convert in your head, or to keep anything that has to happen at a local time on a scheduler with a timezone per job.

cron.job_run_details grows forever until you prune it

Every run writes a row to cron.job_run_details: the job, the command text, status, return_message, start and end time. The README is blunt about it: "The records in the table are not cleaned automatically." One job every 30 seconds is 2,880 rows a day and over a million a year, and it keeps growing after you unschedule the job.

Set your jobs below and watch what a year looks like with and without pruning.

cron.job_run_details growth

6,722 rows a day

Jobs at each cadence
  • Every 30 s1
  • Every minute2
  • Every 5 min3
  • Hourly4
  • Daily2
History kept
Command text

After a year, never pruned

2,453,530 rows

about 585 MB

Kept with 7-day pruning

47,054 rows

about 11.2 MB

0612 monthsnever prunedpruned to 7 days
prune-job.sql
-- Prune nightly at 03:30, keep 7 days
select cron.schedule(
  'prune-cron-history',
  '30 3 * * *',
  $$delete from cron.job_run_details
   where end_time < now() - interval '7 days'$$
);

Sizes are rough: about 250 bytes a row, mostly the command text that pg_cron copies into every run.

Row counts are exact for the cadences chosen. Sizes are a rough estimate (about 130 bytes of row and index overhead plus the command text pg_cron stores in every row).

The fix is one more job, and both the README and AWS's pg_cron docs suggest the same one: delete rows older than a few days, every night. If the table is already huge, the first delete will be slow, so run it once by hand in batches before you schedule it.

Two related levers. cron.log_run = off stops writing history entirely; failures still reach the Postgres log, which is fine if you ship logs somewhere you actually read. And a quick health check is one query away:

select j.jobname, d.status, d.return_message, d.start_time
from cron.job_run_details d
join cron.job j using (jobid)
where d.status = 'failed'
  and d.start_time > now() - interval '1 day'
order by d.start_time desc;

Long-running jobs: queues, overlaps and locks

A cron schedule fires whether or not the last run finished. What happens next depends on who's holding the clock, and pg_cron behaves differently from almost everything else.

pg_cron never runs two copies of the same job. If a run comes due while the previous one is still busy, it's queued and starts the moment the busy one finishes. For cron-expression jobs it queues every tick it missed (an interval job like '30 seconds' queues at most one). A job that sometimes runs long catches up and recovers. A job that is always slower than its schedule builds a backlog that never drains, and each queued run starts later than the one before.

Same slow job, three runners

due every 5 min, 00:00 to 01:00

pg_cron

Queues every tick it could not start, then runs them back to back

Never two at once, but the queue grows: the last run that started was 28 min late and 7 more are still waiting at 01:00.

crontab or HTTP clock, no lock

Starts a new copy on every tick, even while the last one runs

Up to 3 copies run at once, each fighting the others for the same rows and locks.

Same clock + pg_try_advisory_xact_lock

A tick that finds the lock taken exits in milliseconds

One copy at a time and no backlog: 8 ticks found the lock taken and exited.

  • started on time
  • late or overlapping
  • still queued
  • lock taken, exited
One job due every five minutes, for an hour. pg_cron queues; an unguarded crontab or HTTP clock stacks copies; an advisory lock skips the ticks that land on a running job. Drag the duration past five minutes to see them split.

pg_cron's queue protects a job from itself, but not from everything else touching the same rows: a second job, an app worker, a teammate running the same script by hand, or a move from pg_cron to crontab during a migration. A transaction-level advisory lock covers all of those. pg_try_advisory_xact_lock returns false straight away when someone else holds the key, and the Postgres docs note that it's released automatically at commit or rollback, so a crashed run can't leave it stuck:

create or replace function app.roll_partitions() returns void
language plpgsql as $$
begin
  if not pg_try_advisory_xact_lock(hashtext('roll_partitions')) then
    raise notice 'roll_partitions is already running, skipping';
    return;
  end if;
 
  -- DDL waits for locks; don't let it queue behind a long query
  set local lock_timeout = '5s';
  set local statement_timeout = '10min';
 
  -- create next month's partition, detach the old one, ...
end;
$$;
 
select cron.schedule('roll-partitions', '5 0 1 * *', 'select app.roll_partitions()');

The lock_timeout line is the one that saves you at 00:05 on the 1st. A partition create or alter table needs a strong lock, and while it waits behind a long-running report, every new query on that table waits behind it. Failing fast and retrying next time beats freezing the table.

No pg_cron? crontab and psql, pg_timetable, pgAgent or an app worker

On Heroku Postgres or Render, or anywhere you'd rather not restart for an extension, the SQL has to be started from outside the database. Each option moves the clock somewhere else, and each has a cost.

crontab plus psql on a box you own

The oldest answer, and still a good one when you already have a server. One line per job, with flock so a slow run can't stack on top of itself, and a heartbeat ping at the end so silence gets noticed:

# crontab -e on the job runner; password in ~/.pgpass
DATABASE_URL=postgresql://[email protected]:5432/app
 
0 3 * * * flock -n /tmp/prune-events.lock psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "delete from events where created_at < now() - interval '90 days'" && curl -fsS -m 10 https://ping.crontap.com/<token> > /dev/null

-v ON_ERROR_STOP=1 makes psql exit non-zero when the SQL fails, so the && only pings on success. Watch the classic crontab trap: a % in the command is a newline to cron, so escape it as \% (common in to_char formats). And the box itself becomes a dependency: if it's down, so are your jobs. The cron troubleshooting guide covers the rest.

pg_timetable or pgAgent

Both run as a separate process that connects to Postgres and reads its job definitions from tables, so they work where you can't preload a library. pg_timetable is a Go binary from Cybertec: chains of SQL, shell and built-in tasks, cron syntax, and optional concurrency protection. It needs a role with create on the database, not a superuser.

select timetable.add_job(
  'prune-old-events',
  '0 3 * * *',
  $$delete from events where created_at < now() - interval '90 days'$$
);

pgAgent is the pgAdmin-era option: create extension pgagent for the job tables, then a daemon (or Windows service) that polls them every 10 seconds by default. Both are solid, and both mean one more long-running process you deploy, monitor and upgrade.

A worker in your app, or the platform's scheduler

If you already run an app server, a scheduler library in it can hold a connection pool and run the SQL on a timer: node-cron in Node, APScheduler in Python, robfig/cron in Go. It's quick, but the timer lives as long as the process, a deploy can drop a tick, and two replicas run every job twice unless you add a leader election or the advisory lock above. The Node.js cron jobs guide shows that failure mode in detail.

Cloud schedulers move the timer out of your process: Cloud Scheduler calling a Cloud Run function (Google suggests it, next to pg_cron, for pg_partman maintenance on Cloud SQL), or EventBridge Scheduler invoking a Lambda. You pay per run instead of for an idle worker, in exchange for IAM, network access to the database, and a cold start at 03:00.

When the work lives in your app, put an HTTP clock in front of it

pg_cron is a good clock for work that already lives in Postgres. Once the job needs app code (call a payment API, send the emails, write to S3), or you want it tested, retried and reported, it reads better as an HTTP route in your app on an external clock.

The route checks a shared secret, takes the same advisory lock, runs the SQL and returns a status code the scheduler can act on:

app.post("/cron/prune-events", async (req, res) => {
  if (req.get("authorization") !== `Bearer ${process.env.CRON_SECRET}`) {
    return res.sendStatus(401);
  }
  const client = await pool.connect();
  try {
    await client.query("begin");
    const lock = await client.query(
      "select pg_try_advisory_xact_lock(hashtext('prune-events')) as ok"
    );
    if (!lock.rows[0].ok) {
      await client.query("rollback");
      return res.status(200).json({ skipped: "already running" });
    }
    const result = await client.query(
      "delete from events where created_at < now() - interval '90 days'"
    );
    await client.query("commit");
    res.json({ deleted: result.rowCount });
  } catch (err) {
    await client.query("rollback");
    res.status(500).json({ error: err.message });
  } finally {
    client.release();
  }
});

A skipped run answers 200 on purpose: another copy is doing the work, and that isn't a failure worth retrying. A real error answers 500, and that's where an external scheduler earns its place. Crontap retries 5xx responses, timeouts and network errors with exponential backoff by default, records every attempt with its status code and duration, and alerts you once the attempts run out: by email on every plan, or in Slack, Discord or Telegram on paid plans. The schedule carries its own IANA timezone, so 0 3 * * * in Europe/Berlin stays at 03:00 Berlin time through both clock changes, and the same setup works whichever Postgres host is underneath.

For jobs longer than a few minutes, accept the request, hand the work to a queue or background task, and return 202, so a slow night is a slow job and not a timed-out request. Retries are in-process with backoff, not a durable queue, so keep the handler safe to run twice; the lock and a where clause that only touches unfinished rows usually cover it.

Which one should you use

Most teams end up with two: SQL housekeeping in pg_cron, and the jobs people notice on an HTTP clock.

You needpg_croncrontab + psqlpg_timetable / pgAgentHTTP route + external clock (Crontap)
SQL next to the data, no extra processYesNeeds a serverNeeds a daemonNeeds a route in your app
Works on Heroku, RenderNoYesYesYes
Runs more than once a minute1 to 59 s intervalsNopg_timetable intervalsNo, one minute is the shortest
Per-job timezoneOne zone per server, if anyThe box's zoneCheck the tool's docsAny IANA zone per schedule
RetriesNoneNoneLimitedConfigurable, exponential backoff
Someone told when it failsNot built inNot built inNot built inEmail on every plan; Slack, Discord, Telegram on paid
CostIncludedThe serverThe daemon's hostFree for 2 schedules (hourly); Pro from $2.99/mo, every minute

If the job is SQL and silence wouldn't hurt anyone, pg_cron with a prune job is all you need. If it's SQL and silence would hurt, keep pg_cron and add a heartbeat. If it's really app work wearing a SQL hat, give it a route and a clock that tells you when it fails.

Keep reading

FAQ

Postgres cron job questions

Which managed Postgres providers support pg_cron?
As of November 2026: Amazon RDS (PostgreSQL 12.5+), Aurora PostgreSQL (12.6+), Google Cloud SQL, AlloyDB, Azure Database for PostgreSQL flexible server, Neon, Crunchy Bridge, Supabase and DigitalOcean's Standard Edition all list it. Tiger Cloud enables it on request through support. Heroku Postgres and Render Postgres do not offer it.
How do I enable pg_cron on Amazon RDS?
Add pg_cron to shared_preload_libraries in a custom DB parameter group (keep the libraries already there), reboot the instance, then connect to the postgres database as a user with rds_superuser and run CREATE EXTENSION pg_cron. Schedule jobs for other databases with cron.schedule_in_database.
Why does pg_cron say it can only be created in the postgres database?
pg_cron keeps its job table in one database, set by cron.database_name, which defaults to postgres. Either create the extension there and use cron.schedule_in_database to run jobs in your app database, or change cron.database_name (a restart on every host that allows it) and create the extension in your own database.
What timezone does pg_cron use?
GMT by default. Self-hosted Postgres, Azure flexible server and AlloyDB let you change cron.timezone, which needs a restart. Neon interprets every schedule as UTC whatever the setting says, and Cloud SQL does not expose the setting. If you set a zone with daylight saving time, avoid fixed times between 01:00 and 03:00 local, the hours a clock change skips or repeats.
Does cron.job_run_details clean itself up?
No. pg_cron writes one row per run and never deletes them, not even when you unschedule the job. Schedule a nightly delete of rows older than a few days, or set cron.log_run to off if you don't need the history and are happy reading errors from the Postgres log.
What happens if a pg_cron job is still running when it is due again?
pg_cron never runs two copies of the same job. A run that comes due while the previous one is busy is queued and starts as soon as it finishes. For cron-expression jobs every missed tick is queued, so a job that always takes longer than its interval builds a backlog. Interval jobs ('30 seconds') queue at most one extra run.
Can pg_cron run VACUUM?
Yes, as a single-statement command such as 'VACUUM ANALYZE orders'. VACUUM cannot run inside a transaction block, so it cannot sit in a DO block, a function, or a multi-statement command with other SQL. Give it its own job.
Does pg_cron retry failed jobs or alert anyone?
No. A failed run is a row in cron.job_run_details with status failed and the error in return_message, and the job simply runs again at its next scheduled time. To hear about failures, have something read that table, or move the job behind an HTTP route and let an external scheduler such as Crontap retry it and alert you by email, Slack, Discord or Telegram.
What can I use if my host doesn't support pg_cron?
Three options: a crontab entry on a box you control that runs psql, pg_timetable or pgAgent running as a separate process against the database, or an HTTP route in your app that runs the SQL, called by an external scheduler. The HTTP route is the one that also gives you retries, history and alerts without another server to babysit.

The SQL stays in Postgres, the clock moves out

Roll next month's partition at 00:05 on the 1st, London time.

Wrap the maintenance in a small authenticated route, paste its URL, and press Perform test to see the real status code before you save. Postgres keeps doing the work; Crontap keeps the clock in your timezone, retries the failures and alerts you when the attempts run out.

Free for 2 schedules or monitors. No card.

POSThttps://api.your-app.com/cron/roll-partitions
Active

5 0 1 * *Europe/London

Next run in ...

Run history

From the blog

Read the blog

Guides, patterns and product updates.

Tutorials on scheduling API calls, webhooks and automations, plus deep dives into cron syntax, timezones and reliability.

Product

Introducing Crontap status pages

Publish uptime monitors and heartbeats on a public page at crontap.page, pick a template from Clean to a split-flap departures board, and add incidents, maintenance and a badge.

Product

Slack, Discord and Telegram alerts are here

Connect a chat channel once, then route schedule, uptime and heartbeat alerts with defaults, per-job overrides and test sends. See what each alert looks like in Slack, Discord, Telegram and email.

Product Updates

Introducing AI Integrations

Transform a schedule's HTTP response with a plain-English prompt, return text or JSON, and forward it to Slack, Make, n8n, or your own endpoint. Test on any tier; saving is a Pro feature.