pg_cron: Job Scheduling
The pg_cron
extension is a simple cron-based job scheduler for PostgreSQL that runs inside the database.
pg_cron is not fully supported on Fly Postgres. Read more about this Fly Postgres limitation here.
Usage
Enable the extension
- Go to the Database page in the Dashboard.
- Click on Extensions in the sidebar.
- Search for "pg_cron" and enable the extension.
Syntax
The schedule uses the standard cron syntax, in which * means "run every time period", and a specific number means "but only at this time":
You can use [1-59] seconds
as the cron syntax to schedule sub-minute jobs. This is available on pg_cron
v1.5.0+; upgrade your existing Supabase project to use this syntax.
Head over to crontab.guru to validate your cron schedules.
Scheduling system maintenance
Be extremely careful when setting up pg_cron
jobs for system maintenance tasks as they can have unintended consequences. For instance, scheduling a command to terminate idle connections with pg_terminate_backend(pid)
can disrupt critical background processes like nightly backups. Often, there is an existing Postgres setting e.g. idle_session_timeout
that can perform these common maintenance tasks without the risk.
Reach out to Supabase Support if you're unsure if that applies to your use case.
Examples
Delete data every week
Delete old data every Saturday at 3:30am (GMT):
Run a vacuum every day
Vacuum every day at 3:00am (GMT):
Call a database function every 5 minutes
Create a hello_world()
database function and then call it every 5 minutes:
Call a database stored procedure
To use a stored procedure, you can call it like this:
Invoke Supabase Edge Function every 30 seconds
This requires pg_cron
v1.5.0+ and the pg_net
extension to be enabled.
Make a POST request to a Supabase Edge Function every 30 seconds:
Edit a job
Changes the frequency of a job called 'vacuum'
to once every 5 minutes.
Full options for the cron.alter_job()
function are:
It is also possible to modify a job by using the cron.schedule()
function, with the same job name. This will replace the existing job, in the manner of an upsert.
Unschedule a job
Unschedules a job called 'nightly-vacuum'
Viewing previously ran jobs
View the last ten jobs that have ran
The records in cron.job_run_details are not cleaned automatically which will take up disk space in your database.