Run periodic jobs in PostgreSQL
open sourcePostgreSQLself-hostablefree
pg_cron is a cron-based job scheduler for PostgreSQL (10 or newer) that runs inside the database as an extension, made by Citus Data. A background worker reads jobs from the cron.job table and runs each one's SQL command (a statement such as VACUUM or DELETE, or a function or procedure call) on standard cron schedules, with $ for the last day of the month and intervals down to every second. It runs different jobs in parallel but only one instance of each job at a time, records runs in cron.job_run_details, and can schedule jobs in another database of the same server. Managed services including Amazon RDS, Supabase (whose Supabase Cron is built on it), Neon, PlanetScale and Ubicloud document it as a supported extension.
Ways to install
Package managers
Problems it solves
- delete old rows from a Postgres table every night without a separate cron server
- schedule VACUUM or a stored procedure to run inside the database at a set time
- run a SQL function every few seconds from the database itself
- refresh a materialized view on a schedule in Postgres
- schedule recurring maintenance on our managed Postgres where we can't use the server's crontab
- see the history of scheduled database jobs, with which ones failed and why
- process the payroll procedure at noon on the last day of every month in Postgres
- keep scheduled database tasks running after a failover without a separate scheduler box
- schedule SQL jobs in several databases on the same Postgres server
Features
- cron.schedule, cron.schedule_in_database, cron.unschedule and cron.alter_job functions
- standard cron syntax from Vixie cron, plus $ for the last day of the month
- interval schedules from 1 to 59 seconds
- parallel jobs, one instance of each job at a time (a late run is queued)
- run history and status in cron.job_run_details
- jobs run with the scheduling user's permissions; row-level security hides other users' jobs
- libpq connections or background workers to run jobs
- settings for time zone, maximum running jobs, logging and disabling all jobs without a restart
- starts automatically when a hot standby is promoted
- packages for PGDG yum and apt.postgresql.org; builds on Windows
Limitations
- Doesn't run jobs on a hot standby: the scheduler starts only when the server is promoted3
- Doesn't install in more than one database per cluster: jobs for other databases use cron.schedule_in_database3
- Doesn't clean up its run history automatically: cron.job_run_details grows until you delete old rows3
