gitmyhub

pg_cron

C ★ 3.8k updated 2d ago

Run periodic jobs in PostgreSQL

pg_cron is a PostgreSQL extension that lets you schedule SQL commands to run automatically on a timer, similar to how a system cron job works on a Unix server. The difference is that everything runs inside your database rather than on the operating system. You install it once, add it to PostgreSQL's startup configuration, and then create scheduled jobs using ordinary SQL function calls.

Schedules use the familiar five-field cron syntax: minute, hour, day of month, month, and day of week. You can also write shorthand like "30 seconds" or "5 seconds" to run a job on a sub-minute interval. A special dollar sign character represents the last day of the month, which is useful for end-of-month processing tasks. The project links to crontab.guru, a web tool that helps you construct and verify cron expressions.

Creating a job is a single SQL call. You pass a schedule string and any SQL command, from a simple DELETE or VACUUM to a stored procedure call. Jobs get a numeric ID and an optional name. You can remove a job by name or ID using cron.unschedule, change its schedule or command later using cron.alter_job, or pause it by setting it to inactive. A row-level security policy on the jobs table means each database user only sees and controls their own jobs unless they are a superuser.

Jobs are stored in a table called cron.job. A background worker process wakes up periodically, reads the table, and fires any jobs whose schedule matches the current time. Multiple jobs can run at the same time, but each specific job runs only one instance at a time; if a second trigger arrives before the first finishes, it waits in a queue.

The extension is available as a packaged install on Red Hat, Debian, and Ubuntu systems. It is also supported directly by several managed database providers including Amazon RDS, Azure Database for PostgreSQL, Supabase, and Crunchy Bridge.