The goal
You want nightly maintenance inside the database: purge old rows, refresh a materialized view, run VACUUM ANALYZE on a hot table. You don't want a cron box or an Agent-style server that someone forgets to patch. pg_cron runs cron-syntax jobs from a background worker inside PostgreSQL, so the schedule fails over and is backed up along with the database.
This post covers installing it, scheduling jobs correctly, finding failed runs, and the housekeeping people skip.
Step 1: install and enable pg_cron
pg_cron must be loaded at server start. It runs in one database, postgres by default. You create the extension there and schedule every job from there.
Self-managed
Install the package for your major version (for example postgresql-17-cron on Debian/Ubuntu from the PGDG repo), then edit postgresql.conf:
shared_preload_libraries = 'pg_stat_statements,pg_cron' # keep what is already there
cron.database_name = 'postgres'
cron.timezone = 'UTC' # schedules are read in this time zone
Restart, then:
CREATE EXTENSION pg_cron; -- run in the database named by cron.database_name
SELECT extversion FROM pg_extension WHERE extname = 'pg_cron';
Amazon RDS / Aurora PostgreSQL
Add pg_cron to shared_preload_libraries in a custom parameter group and reboot:
aws rds modify-db-parameter-group \
--db-parameter-group-name pg17-custom \
--parameters "ParameterName=shared_preload_libraries,ParameterValue='pg_stat_statements,pg_cron',ApplyMethod=pending-reboot"
aws rds reboot-db-instance --db-instance-identifier orders-db
For Aurora, use the cluster parameter group. Then run CREATE EXTENSION pg_cron; as a user with the rds_superuser role.
Azure Database for PostgreSQL Flexible Server
Allow-list the extension, preload it, then restart:
az postgres flexible-server parameter set -g rg-data -s orders-pg \
--name azure.extensions --value PG_CRON,PG_STAT_STATEMENTS
az postgres flexible-server parameter set -g rg-data -s orders-pg \
--name shared_preload_libraries --value pg_cron,pg_stat_statements
az postgres flexible-server restart -g rg-data -n orders-pg
Warning
Each
parameter setcall replaces the whole value. Read the current value first (az postgres flexible-server parameter show ... --name shared_preload_libraries) and append to it. If you drop a library another feature depends on, that feature breaks at the next restart.
Step 2: schedule jobs
The schedule uses the standard five-field cron syntax: minute, hour, day of month, month, day of week. Give every job a name. If you schedule a job with a name that already exists for your user, pg_cron updates that job instead of adding a duplicate, so your scripts can be re-run safely.
-- Nightly purge in the postgres database itself
SELECT cron.schedule('purge-audit-90d', '15 2 * * *',
$$DELETE FROM audit.events WHERE created_at < now() - interval '90 days'$$);
-- Run a job in a different database (pg_cron itself lives in postgres)
SELECT cron.schedule_in_database('vacuum-orders', '30 3 * * *',
'VACUUM (ANALYZE) public.orders', 'ordersdb');
SELECT cron.schedule_in_database('refresh-daily-sales', '*/30 * * * *',
'REFRESH MATERIALIZED VIEW CONCURRENTLY reporting.daily_sales', 'ordersdb');
Interval schedules such as '30 seconds' are available in pg_cron 1.5 and later. Check extversion before you use them.
List, change and remove jobs:
SELECT jobid, jobname, schedule, database, username, active, command
FROM cron.job ORDER BY jobname;
SELECT cron.unschedule('purge-audit-90d'); -- by name (or by jobid)
Rules that avoid most problems
- A job runs as the user who scheduled it. Schedule purge jobs as the application owner role, not as a superuser.
- Keep long logic in a procedure (
CALL maint.purge_audit()) so the job command stays short and you can version the code. - Delete in batches. A single 50-million-row
DELETEholds locks, bloats the table and floods WAL to the replicas. - pg_cron won't start a second run of a job while the previous run is still going. A slow job therefore skips slots rather than stacking up, so don't schedule it tighter than it can finish.
Step 3: find failed and slow runs
Every run is recorded in cron.job_run_details (unless cron.log_run = off).
-- Failures in the last 24 hours
SELECT j.jobname, d.status, d.start_time, d.end_time, d.return_message
FROM cron.job_run_details d
JOIN cron.job j USING (jobid)
WHERE d.status = 'failed'
AND d.start_time > now() - interval '24 hours'
ORDER BY d.start_time DESC;
-- Last run and duration per job
SELECT DISTINCT ON (j.jobname)
j.jobname, d.status, d.start_time,
d.end_time - d.start_time AS duration
FROM cron.job j
LEFT JOIN cron.job_run_details d USING (jobid)
ORDER BY j.jobname, d.start_time DESC;
-- Runs that are still "running" after two hours
SELECT jobid, runid, job_pid, start_time, command
FROM cron.job_run_details
WHERE status = 'running' AND start_time < now() - interval '2 hours';
To stop a stuck run, cancel its backend with SELECT pg_cancel_backend(<job_pid>);. Use pg_terminate_backend only if the cancel doesn't take effect.
Common failures
Symptom in return_message or the log | Cause | Fix |
|---|---|---|
connection failed | The worker connects over libpq to localhost and pg_hba.conf rejects it, or there is no password available | Add a local rule for the job owner, use a .pgpass file, or set cron.use_background_workers = on (and raise max_worker_processes) |
permission denied for table ... | The job runs as the scheduling user, who has no rights on the object | Grant the rights to that role, or schedule the job as the object owner |
relation ... does not exist | The job ran in postgres, not in the application database | Recreate it with cron.schedule_in_database |
| Job never runs, nothing in history | active = false, wrong cron.timezone, or the extension isn't in cron.database_name | Check cron.job.active, SHOW cron.timezone, and where the extension is installed |
server restarted | The instance restarted or failed over during the run | Make the job idempotent so the next run finishes the work |
| Jobs stop after failover on self-managed HA | The pg_cron worker only runs on the primary | Expected. Jobs resume on the new primary, so make sure the package is installed on every node |
Tip
REFRESH MATERIALIZED VIEW CONCURRENTLYneeds a unique index on the view. Without one, every run fails with an error and the data quietly goes stale. Check the failure query above after you add any new refresh job.
Step 4: keep the history table small
pg_cron never purges cron.job_run_details. A job that runs every minute adds over half a million rows a year, and the queries above get slower. Schedule the cleanup with pg_cron itself:
SELECT cron.schedule('purge-cron-history', '0 4 * * *',
$$DELETE FROM cron.job_run_details WHERE end_time < now() - interval '14 days'$$);
If you only need failures, you can set cron.log_run = off and rely on the server log (cron.log_statement, on by default). That makes the SQL checks above impossible, though, so most teams keep log_run on and purge the table instead.
Step 5: alert on it
Point your monitoring tool at a single query that returns rows only when something is wrong:
SELECT j.jobname, max(d.start_time) AS last_failure
FROM cron.job_run_details d
JOIN cron.job j USING (jobid)
WHERE d.status = 'failed' AND d.start_time > now() - interval '1 hour'
GROUP BY j.jobname;
Also alert when a critical job has no successful run within its expected window. That catches a job that was deactivated or unscheduled, which leaves no failure row.
Prevent it next time
- Keep every
cron.schedulecall in a versioned SQL script and run it after each restore or rebuild. Named jobs make the script idempotent. - Check
SHOW cron.timezoneonce per server, and write schedules in UTC. - Review
cron.jobduring change reviews: who owns each job, what it touches and whether it is still needed. - After a major version upgrade, confirm the pg_cron package is installed for the new version and run
ALTER EXTENSION pg_cron UPDATE;. - Pair purge jobs with a look at bloat and autovacuum. Deleting rows doesn't give the space back to the OS. See the PostgreSQL DBA cheat sheet for the vacuum and bloat queries.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get