What is pg_cron and how do you schedule jobs in PostgreSQL?

Answer

pg_cron is a PostgreSQL extension that acts as a cron scheduler running inside the database. It allows scheduling SQL queries and stored procedure calls directly from PostgreSQL without external schedulers. Install: CREATE EXTENSION pg_cron;. Add a job: SELECT cron.schedule('nightly-vacuum', '0 3 * * *', 'VACUUM ANALYZE orders');. Schedule uses standard cron syntax (minute, hour, day, month, weekday). Run every 5 minutes: '*/5 * * * *'. View jobs: SELECT * FROM cron.job;. View history: SELECT * FROM cron.job_run_details ORDER BY start_time DESC LIMIT 20;. Remove: SELECT cron.unschedule(job_id);. Runs in the database as a background worker. Useful for: refreshing materialized views, purging old data, generating reports, and running maintenance tasks.