2.5 Hours

14. Scheduled Jobs with pg_cron

Automation

Database-Level Scheduling Without External Services

pg_cron is a Postgres extension that runs SQL commands or calls functions on a schedule, directly inside the database. No Lambda functions, no cron services — your scheduled jobs live in the same place as your data, with full access to Postgres transactions and no cold starts.

Many applications need scheduled tasks: cleaning up expired sessions, computing daily statistics, refreshing materialized views, processing queues, or generating invoices. Traditionally, you'd run these on a separate server or using a cloud scheduler. pg_cron eliminates this complexity. Jobs run inside the database, have full transactional access to your data, and are reliable. pg_cron uses standard cron syntax for scheduling. Jobs can be created, listed, and removed with simple SQL commands. The job history is stored in cron.job_run_details for monitoring. This is a powerful tool for automating database maintenance and business workflows. It simplifies your architecture by reducing external dependencies.

Scheduling Jobs

Scheduling a job is simple. Use cron.schedule() with a name, cron expression, and the SQL to execute. The cron expression follows standard cron syntax: minute hour day month weekday. For example, 0 3 * * * means 3 AM daily. */5 * * * * means every 5 minutes. All times are UTC. You can run any SQL — DELETE, UPDATE, SELECT, or function calls. Use dollar-quoting for multi-statement SQL. View your jobs in cron.job. Check execution history in cron.job_run_details. Remove a job with cron.unschedule(). pg_cron is pre-installed on Supabase, so you can use it immediately. It's reliable and efficient — jobs run in the database process with minimal overhead. This is the simplest way to add scheduled tasks to your Supabase project.

SQL
-- Enable pg_cron (pre-installed on Supabase)
CREATE EXTENSION IF NOT EXISTS pg_cron;

-- Run a cleanup job every day at 3am UTC
SELECT cron.schedule(
  'cleanup-expired-sessions',
  '0 3 * * *',
  $$DELETE FROM sessions WHERE expires_at < NOW()$$
);
Cron Syntax:pg_cron uses standard cron syntax: Minute Hour Day Month Weekday. Examples: <strong><code>0 0 * * * = midnight daily, <strong><code>*/15 * * * * = every 15 minutes, <strong><code>0 9 * * 1 = 9am every Monday. All times are UTC.

Common Use Cases

pg_cron handles many common scheduling needs. Expiry cleanup deletes expired sessions, tokens, and OTPs. Aggregation computes daily or weekly statistics into summary tables for fast dashboards. Queue processing picks up and processes jobs from a queue table. Materialized view refresh keeps pre-aggregated views fresh. Billing cycles generate invoices and check subscription renewals. Data sync periodically syncs data to external services via pg_net. These use cases cover most background job needs. By using pg_cron, you avoid the complexity of external schedulers. Your jobs run inside the same transaction as your data — no network latency, no cold starts. This is a significant advantage for time-critical operations.

  • Expiry cleanup: Delete expired sessions, tokens, OTPs, soft-deleted records past retention period.
  • Aggregation: Compute daily/weekly statistics into summary tables for fast dashboard queries.
  • Queue processing: Pick up and process jobs from a queue table on a schedule.
  • Materialized view refresh: Keep pre-aggregated views fresh for analytics workloads.
  • Billing cycles: Generate invoices, check subscription renewal dates, flag overdue accounts.

Knowledge Check

Ready to test your understanding of 14. Scheduled Jobs with pg_cron?

Back