pg_cron Scheduling: Setup & Usage Guide
In this article
pg_cron is a PostgreSQL extension that lets you schedule SQL commands and functions directly inside your database, using cron-like syntax. Instead of relying on external cron jobs or application-level schedulers, you can define recurring jobs that are stored and managed within PostgreSQL itself. This is useful for periodic maintenance tasks like vacuuming, refreshing materialized views, archiving old data, or generating reports. To use it, you need PostgreSQL 10 or higher, and the extension must be installed on your server (usually via the `postgresql-contrib` package).
What You'll Need
- A PostgreSQL server (version 10 or later) with superuser or appropriate privileges to install extensions.
- The `pg_cron` extension installed on the server (commonly available in the `postgresql-contrib` package).
- Command-line access to the server (e.g., `psql`) or a SQL client.
- For Linux: the `cron` daemon must be running, as pg_cron relies on it.
Step-by-Step
- Install the extension package. On Debian/Ubuntu, run `sudo apt install postgresql-contrib`. On RHEL/CentOS, use `sudo yum install postgresql-contrib`. For other systems, consult your package manager.
- Add `pg_cron` to `shared_preload_libraries`. Edit your `postgresql.conf` file (usually in `/etc/postgresql/
/main/` or `/var/lib/pgsql/data/`). Find the line `#shared_preload_libraries = ''` and change it to `shared_preload_libraries = 'pg_cron'`. If the line already has other libraries, add pg_cron separated by a comma, e.g., `shared_preload_libraries = 'pg_cron, pg_stat_statements'`. - Restart PostgreSQL. Use `sudo systemctl restart postgresql` (or `service postgresql restart`). This is required because the extension must be loaded at server start.
- Create the extension in your database. Connect to your database as a superuser (e.g., `sudo -u postgres psql`) and run: `CREATE EXTENSION pg_cron;`. If you want to use pg_cron in multiple databases, you need to create the extension in each one.
- Verify the installation. Run `SELECT cron.job;` to see an empty job list. If you get an error, the extension isn't loaded correctly.
- Schedule your first job. Use the `cron.schedule` function. For example, to run a vacuum every day at 2 AM, run:
SELECT cron.schedule('daily-vacuum', '0 2 * * *', 'VACUUM;');The first argument is a unique job name, the second is the cron schedule (minute hour day-of-month month day-of-week), and the third is the SQL command. - Check the job status. Query `cron.job` to see all scheduled jobs, and `cron.job_run_details` to see the history of executions and their success/failure status.
- Modify or unschedule a job. To change a job's schedule, use `cron.unschedule(job_name)` then reschedule with new parameters. To remove a job permanently, use `cron.unschedule(job_name)`.
Common Mistakes
- Forgetting to restart PostgreSQL after adding pg_cron to `shared_preload_libraries`. The extension won't work until the server is restarted.
- Using the wrong cron syntax. pg_cron uses standard five-field cron syntax: minute (0-59), hour (0-23), day of month (1-31), month (1-12), day of week (0-6, where 0 is Sunday). Mixing up the order is a frequent error.
- Not using a unique job name. If you schedule two jobs with the same name, the second one will fail because the name already exists.
- Running commands that require a transaction context. pg_cron runs each job in its own transaction. Commands like `VACUUM` cannot run inside a transaction block in some PostgreSQL versions, so you may need to use `VACUUM;` alone (which is allowed) or wrap it in a function that uses `dblink` or `pg_background` to run outside the transaction.
- Assuming jobs run in the database where they were created. By default, jobs run in the same database where the extension was created, but you can specify a different database using the `database` parameter in `cron.schedule`.
Tips
- Use the `cron.schedule` function with a named schedule to easily manage jobs. For example, `SELECT cron.schedule('nightly', '0 3 * * *', 'REFRESH MATERIALIZED VIEW my_mv;');`
- Test your SQL command manually before scheduling it. This helps avoid failures due to syntax errors or missing privileges.
- Monitor job runs by querying `cron.job_run_details`. You can filter by `status` ('succeeded' or 'failed') to see which jobs need attention.
- If you need to run a job that requires superuser privileges, schedule it as a superuser. Jobs run with the privileges of the user who scheduled them.
- For complex multi-step jobs, create a stored procedure or function and schedule a single call to it.
Troubleshooting
Job doesn't run at all. First, check that the `cron` daemon is running on Linux (`pgrep cron`). If not, start it with `sudo systemctl start cron`. Then verify that pg_cron is loaded by running `SHOW shared_preload_libraries;` – it should include 'pg_cron'. If not, you missed the restart step.
Error: “pg_cron can only be created in the postgres database”. In some installations, pg_cron must be created in the `postgres` database. If you get this error, connect to `postgres` and run `CREATE EXTENSION pg_cron;`, then schedule jobs from that database.
Job fails with a permission error. The user who scheduled the job needs appropriate privileges on the objects referenced in the SQL. Grant necessary permissions or schedule the job as a superuser.
Job runs but has no effect. Check `cron.job_run_details` for the return message. If the command is a `VACUUM` or `ANALYZE`, it might be skipped if there's nothing to do. Also, ensure the job is running in the correct database – use the `database` parameter in `cron.schedule` to specify it explicitly.
Cannot create extension: permission denied. You need superuser privileges to create the extension. Log in as the `postgres` user or a user with superuser rights.
Frequently Asked Questions
Can I schedule a job to run every minute?
Yes, the cron syntax allows `* * * * *` for every minute. However, be mindful of the load on your server.
How do I see all scheduled jobs?
Run `SELECT * FROM cron.job;` to list all jobs with their schedules and commands.
Can I schedule a job in a different database than the one where I created the extension?
Yes, use the `database` parameter in `cron.schedule`. For example: `SELECT cron.schedule('job-name', '0 0 * * *', 'UPDATE table SET ...', 'my_other_db');`
What happens if my server is down when a job is supposed to run?
pg_cron does not catch up on missed jobs. If the server is down at the scheduled time, that execution is skipped. The next scheduled time will run normally.
Can I use pg_cron with Amazon RDS or other managed services?
Some managed services like Amazon RDS for PostgreSQL support pg_cron, but you may need to enable it via a parameter group. Check your provider's documentation.
Does pg_cron support time zones?
Yes, you can set the time zone for the cron daemon using the `cron.timezone` configuration parameter in `postgresql.conf`. By default, it uses the server's time zone.