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.
Previous
How do you implement partitioned tables efficiently in PostgreSQL?
Next
How do you use EXPLAIN ANALYZE effectively in PostgreSQL?
More PostgreSQL Questions
View all →- Advanced What is the query planner in PostgreSQL and how does it work?
- Advanced What causes poor query plans and how do you fix them?
- Advanced What is logical replication in PostgreSQL?
- Advanced How do you implement row-level security (RLS) in PostgreSQL?
- Advanced What is table bloat in PostgreSQL and how do you fix it?