When teams schedule PostgreSQL maintenance with pg_cron
Teams usually reach for pg_cron when partition rotation, materialized view refreshes or vacuum-style maintenance is run by hand or by a cron host outside the database, and that outside job has become hard to see, hard to audit and easy to forget after a staff change. pg_cron is a cron-based job scheduler for PostgreSQL 10 or higher that runs inside the database as an extension. A background worker tracks scheduled jobs in the cron.job table, and the scheduling code comes from Paul Vixie's cron, so the familiar cron syntax applies. Teams implement it when they want the schedule, the SQL and the run history to live beside the data they maintain.
The module is released under the PostgreSQL License, a permissive license similar to the BSD or MIT licenses, and DeployOpen delivers it inside your own infrastructure, so the extension, its build and its schedule sit under your change control. Before you commit, confirm with your DBA team that your PostgreSQL packaging offers the extension for your exact major version, and that the database role creating jobs has the privileges your maintenance tasks need. Also decide whether jobs will touch only the default database or other databases on the same cluster, since that choice affects who can see and change each job.
The main risk is an in-database scheduler that quietly fails with its server. If the primary is down, scheduled work stops, and a standby does not run the job unless you plan for that case. Confirm how your failover design handles scheduled jobs before you move maintenance into the database, and list which jobs must run on the primary only. Ask your team to name the owner of every job, the expected run window and the action taken when a job fails.
What pg_cron does inside the database
pg_cron runs scheduled SQL inside PostgreSQL itself, so the job definitions, the scheduler and the run records live next to the data they touch. The six areas below cover what the extension does, where its boundaries sit, and what your team should confirm before relying on it in production.
Cron-syntax scheduling
Jobs are defined with the same schedule syntax as the Unix cron utility, because the scheduling code comes from Paul Vixie's cron. A schedule such as 0 3 * * * runs a statement at 03:00 each day. Check how your team reads the time zone the scheduler uses and test any schedule that crosses a daylight saving change before it reaches production.
The background worker
pg_cron runs a background worker process inside the PostgreSQL server that wakes up and starts jobs when their schedules are due. Because the worker belongs to the server, it stops when the server stops and it needs the extension loaded at startup. Confirm the worker settings for your PostgreSQL version and include the worker's status in your health checks.
The cron.job registry
Each scheduled job is recorded as a row in the cron.job table, which holds the schedule, the command and the database and user it runs under. Because the registry is an ordinary table, you can review and audit it with SQL and include it in change control. Restrict who can write to it, since any row there becomes code that runs on a schedule.
Running SQL against the database
A job's command is SQL text that the worker executes, such as a call to a maintenance function, a partition rotation or a materialized view refresh. Keep each command short and idempotent so a retry after a failed run does not duplicate work. Test commands in a non-production copy first, because a scheduled statement runs without an operator watching it.
Jobs in other databases
A job runs in the database where the extension is installed by default, and the repository documents a way to schedule work in other databases on the same server. Confirm the exact setting and its privilege requirements for your version in the repository documentation. Plan which database holds the extension, since that choice decides where the registry and run history live.
pg_cron repositoryJob run history
pg_cron records each execution in a run history table, with its status, start and end times and any error message. This record is the first place to check when a refresh or rotation did not happen. Decide how long to keep run records, since the table grows with every run, and alert on failed runs rather than reading the table by hand.
Configuration decisions before installing pg_cron
This table compares the choices to settle before pg_cron goes into a cluster, with the options for each and when they fit. Read it as a checklist: resolve the hosting database and ownership model first, because they determine how the other decisions play out.
| Decision | Options | When it fits |
|---|---|---|
| Hosting database | A single dedicated maintenance database, or the application database itself | A dedicated database keeps cron.job and job history in one place. Hosting in the application database keeps jobs next to the data they touch, but spreads scheduling across environments. |
| Job ownership and role | Superuser-owned jobs, or jobs run by a least-privilege role | Use a dedicated role with only the grants each job needs when jobs only read or write specific schemas. Superuser ownership suits short-lived admin tasks that a DBA reviews. |
| Schedule granularity | Standard five-field cron expressions, or sub-minute intervals | Standard cron syntax suits maintenance, partition rotation and refresh jobs. Confirm in the pg_cron documentation whether your version supports second-level scheduling before designing around it. |
| Overlap handling | Let runs overlap, or design jobs to be idempotent and skip if still running | Overlap is a risk for long refresh or rotation jobs. Make each job safe to re-run and use locks or status checks in the SQL when runs may exceed their interval. |
| Cross-database jobs | Schedule per database from the hosting database, or run each job in its target database | pg_cron runs jobs in the database named at scheduling time. Confirm how cross-database targeting is configured for your version before relying on it for multi-database estates. |
| Run history retention | Keep history indefinitely, purge on a schedule, or keep history for a fixed review window | Unbounded history grows cron.job_run_details. Choose a retention window that matches your audit and troubleshooting needs, and schedule the purge as its own job. |
| Job body: SQL or scripts | SQL and functions inside the database, or calls to external scripts | SQL suits maintenance inside the database with simple dependencies. External scripts suit jobs that call APIs, move files or need retries and alerting beyond what the database provides. |
| Scheduler scope | pg_cron only, or pg_cron plus an external scheduler | Use pg_cron when jobs depend on database state and must run where the data lives. An external scheduler fits multi-system workflows, dependency graphs and centralized alerting. |
How the background worker and cron.job table run each job
The core of pg_cron is a chain of four steps: the extension is loaded at server start, a background worker wakes up on a schedule, it reads job definitions from the cron.job table, and each run is recorded so you can see what happened. Getting the first step right matters most. pg_cron has to be listed in shared_preload_libraries and the server restarted before the worker starts, and CREATE EXTENSION pg_cron is run afterward in the database that holds the cron.job table. Setting shared_preload_libraries alone does not create the table, and creating the extension alone does not start the worker. Confirm both steps on your own instance before you rely on any schedule.
Before you install, confirm three things with your own environment rather than assuming them. First, check that your PostgreSQL major version is one the pg_cron build supports (the topic sources state version 10 or higher) and that your packages match that major version. Second, confirm how your platform ships the extension: an official package, a managed service that may restrict shared_preload_libraries, or a container image you build. Third, confirm the database name pg_cron uses for its metadata, since that setting decides where cron.job lives and must be set in the server configuration. Record the answers in the change ticket so an upgrade or rebuild does not silently drop the worker.
Worker and connection settings belong in the capacity plan, not in a later tuning pass. Each job holds a database connection while it runs, and the background worker consumes a slot from the server's background worker limit. A schedule that starts many jobs at the same minute can exhaust connections or workers and delay other maintenance. Put the number of concurrent jobs, their expected run time and the connection limit together in one table, and review it whenever a new job is added. For details on the pg_cron repository and its current setting names, read the pg_cron repository and confirm the values against the release you deploy.
How a scheduled job moves from cron.job to the database
A job starts as a row in the cron.job table, written through the extension's scheduling interface. The pg_cron background worker reads that table, decides when each job is due, and runs the SQL in the target database. Jobs can also be pointed at a different database on the same server, so the target is a setting you check, not an assumption. Run history is written to a separate log table and should feed your monitoring, because a job that fails silently is the most common surprise.
Data path from a job definition to its execution, run record and monitoring.
How a pg_cron rollout runs from inventory to handover
The sequence moves scheduled work from scattered cron hosts and tickets into a documented, monitored set of jobs inside PostgreSQL, with an explicit list of what stays outside the database. Each step closes with a check the owning team can sign off.
Inventory scheduled work and owners
Collect every recurring task that touches the database: crontab entries on database and application hosts, Kubernetes CronJobs, scheduler tools, and SQL scripts that someone runs by hand. For each one, record the SQL or command it runs, the database and role it uses, the schedule, the business owner, and what breaks if it stops. The output is a single inventory that the database team and application owners both have read and corrected. The step is done when every entry has a named owner and no job is listed as unknown.
Decide which jobs stay external
Sort the inventory into jobs that suit pg_cron and jobs that belong in an external scheduler. Jobs that only run SQL inside one cluster, such as vacuum helpers, partition rotation calls or materialized view refreshes, are usually good candidates. Jobs that call HTTP services, move files between hosts, depend on another system's completion, or need retries across several targets often stay outside. The output is a decision register that names each job, its destination, and the reason. Confirm the decision with the owners before any extension is installed.
Confirm packaging and version support in a test environment
Install the pg_cron package in a test cluster that matches the production PostgreSQL major version and operating system. The extension's upstream repository states that it supports PostgreSQL 10 or higher, so confirm the exact package version against your PostgreSQL major with your package source or vendor documentation. Check that the extension loads, that the shared library is preloaded, and that the scheduler starts without errors in the server log. The output is a short test record showing the installed version, the PostgreSQL version, and a successful load.
Configure the background worker and permissions
Set the shared preload configuration and the database that hosts the cron.job metadata table, then restart PostgreSQL so the background worker starts. Create a dedicated role for scheduling, grant it only the privileges each job needs, and decide which role owns the job rows. Review the configuration keys in your version's documentation, because the names and defaults are the source of truth for your build. The output is a reviewed configuration file and a role map showing who can create, alter, and remove jobs.
Build and review jobs in a staging database
Create each job in staging using the cron schedule syntax, which follows the same format as Paul Vixie's cron. Schedule jobs against the staging copy, then check the cron.job table and the job run history to confirm that each job fires at the expected time and records the expected outcome. Ask a second engineer to review each SQL body for locking, long transactions, and effects on replicas. The output is a reviewed job definition set, with each job's test result recorded next to its entry in the decision register.
Enable production schedules with monitoring
Load the reviewed job definitions into production during a low-risk window agreed with the owners, and enable them in a defined order so that a problem with one job does not hide the others. Set up alerts for failed runs, jobs that overrun their expected window, and a missing run that should have happened. Watch the first full cycle of each schedule, including any monthly or weekly job, before marking it accepted. The output is a production job list with alerting confirmed by a deliberate test failure.
Document and hand over to the operating team
Write a runbook that covers the job register, the owner of each job, the commands used to pause, change, and remove a job, how to read run history, and the escalation path when a run fails. Walk the operating team through the runbook and have them perform one pause and one resume on a test job. Record the review date and the next review trigger, such as a PostgreSQL major upgrade or an extension update. The output is a signed handover pack that the database team and job owners have accepted.
What drives pg_cron implementation effort and cost
This table lists the factors that change the effort of a pg_cron rollout, who carries each piece of work, and whether it is one-time or recurring. Read it as a checklist for scoping an internal build or comparing partner quotes, since the same job count can produce very different effort depending on the rows below.
| Driver | Why it changes effort or cost | What to ask for in a quote |
|---|---|---|
| Job count and complexity | Each job needs a schedule, a SQL body, error handling and a retention decision. Jobs that call functions, depend on other jobs or touch large tables take longer to design and test than a single vacuum or refresh statement. | A job inventory listing schedule, target object, expected run time and failure behavior for each job |
| Number of target databases | pg_cron runs in one database and reaches others through its database setting, so each additional target adds grants, connection settings, testing and a separate place to check run history. | The list of target databases, the role each job runs as in each one, and how grants are reviewed |
| Change control around SQL in jobs | Job bodies are stored in the cron.job table and can change without an application release. Teams usually need a versioned source of truth, review of each change and a rollback path, which adds process work at the start and small recurring effort later. | How job definitions are stored in version control, who approves changes, and how a bad change is reverted |
| Monitoring and alerting integration | The run history in cron.job_run_details must be exported or queried by the monitoring stack. Alerts on failed or missed runs need thresholds agreed with the operations team, which takes design time and tuning after go-live. | Which metrics or log lines are collected, the alert rules delivered, and who receives them out of hours |
| Packaging across environments | Development, test and production need the same extension version, the same job definitions and environment-specific settings. Differences between environments are a common source of late surprises and rework. | How the extension and job definitions are installed in each environment and how drift is detected |
| PostgreSQL upgrades | The extension must be matched to the PostgreSQL major version, and jobs must be retested after an upgrade. Teams planning a major upgrade should include pg_cron in the test plan, not only the application queries. | Which PostgreSQL versions are in scope, how extension versions are pinned, and how job tests are repeated after an upgrade |
| Audit trail for compliance | Assessors often ask who created or changed a scheduled job, when it ran and what it changed. Producing that evidence needs logging, retained run history and records of approvals, which must be designed before the first production job. | Which run history and change records are retained, for how long, where they are stored and how they are produced on request |
| One-time versus recurring work | Design, build, testing and initial documentation are one-time costs. Job changes, alert tuning, extension updates and periodic restore or run reviews recur for as long as the jobs run. | Separate line items for one-time build and recurring operations, with the scope and frequency of each recurring item stated |
When an external scheduler is the better fit
When should I use an external scheduler instead of pg_cron?
Use an external scheduler when the work spans several systems, needs tooling outside SQL, or must follow a dependency graph with retries across services. pg_cron is a good fit for jobs that are SQL statements against one PostgreSQL cluster, such as vacuum-style maintenance, partition rotation and materialized view refreshes. Once a job must wait for a file transfer, call an API, or run only after another team's pipeline finishes, the database is no longer the natural place to coordinate it. Weigh the work against the jobs you actually run, not the jobs you might add later.
Does pg_cron handle job dependencies and retries?
pg_cron runs each scheduled command on its own schedule and records the result in the job run history, but it does not model dependencies between jobs. If job B must start only after job A succeeds, you need to encode that logic yourself, for example with a status table that the second job checks before it runs. Retry behavior is also left to your SQL. For graphs with branches, conditional retries and backfills, a workflow orchestrator designed for that purpose is easier to reason about and audit.
Which jobs should not run inside the database at all?
Jobs that need non-SQL tooling, that call external services, or that process large files should run outside the database. Examples include pulling files from object storage, running Python or Java code, sending notifications, or calling a third-party API for rate-limited data. Keeping these jobs out of PostgreSQL also avoids tying their failures and resource use to the database process. Calling them from the database through extensions adds a dependency you would have to secure, patch and test with every PostgreSQL upgrade.
When does a central scheduler across many services make sense?
A central scheduler is worth considering when several applications, databases and data platforms need one place to define schedules, owners, alerts and run history. Per-database scheduling works well for a single cluster, but when operations teams must see every scheduled job across dozens of systems from one console, scattered cron entries become hard to govern. Ask whether the scheduler must integrate with your identity provider, produce audit trails for each job, and separate who can change schedules from who can run them. Those requirements usually decide the tool more than job count does.
Can an external scheduler still run SQL against PostgreSQL?
Yes. Most external schedulers connect to PostgreSQL with a dedicated, least-privilege role and run the same SQL you would otherwise place in pg_cron. The trade-off is where the schedule lives and who can see it. An external scheduler adds a separate service to deploy, secure, back up and monitor, plus its own connection to the database that counts against connection limits. Use a connection pooler such as PgBouncer where many short jobs connect at once, and confirm the scheduler's own high availability plan so a single scheduler outage does not silently stop maintenance.
Where do pipeline DAGs with task-level control fit in this decision?
DAG-level control is what an orchestrator adds beyond a scheduler: task graphs, sensors that wait for conditions, backfills for past intervals, and per-task retries with logs. For scheduled data pipelines that need that control, see the DeployOpen page on Apache Airflow, which covers executors, DAG delivery, secrets and SSO for infrastructure you control. Keep simple in-database maintenance in pg_cron even when Airflow is present, so routine vacuum and partition work does not depend on pipeline health.
What does it cost to run a separate scheduler?
The license cost of most open-source schedulers is zero, but the operating cost is not. You pay for the deployment work, the hosts or containers, the database role and network rules, monitoring, upgrades and the time someone spends maintaining job definitions. These costs recur as the scheduler and PostgreSQL move through versions. Ask any implementation partner for a quote that separates one-time build work from ongoing support, and that lists which systems the scheduler will touch, since that count drives both effort and risk.
How pg_cron connects to the rest of the platform
pg_cron runs jobs where the data lives, but most jobs touch tools around the database: partition managers, materialized views, audit logs, metrics and backups. Each card below names one connection and what to verify before the job goes into production.
Partition rotation with pg_partman
Scheduled rotation of time-based partitions is usually handled by pg_partman's maintenance function, which pg_cron can call on a fixed schedule. Confirm which job creates future partitions and which drops or detaches old ones, so two schedulers never act on the same tables. Check that the pg_partman version matches your PostgreSQL major version, and test retention settings in a non-production copy before enabling deletes.
Refresh jobs for materialized views
A refresh job runs REFRESH MATERIALIZED VIEW on a schedule, and the choice between a plain and a concurrent refresh decides whether readers are blocked. Concurrent refresh requires a unique index on the view. Confirm the expected refresh duration against the schedule interval, and make sure a slow run cannot overlap the next one.
pgAudit and log shipping for job activity
Jobs that change data or grant privileges should appear in your audit trail. pgAudit records statements executed by jobs, but job runs also need to be retained in the cron.job_run_details table or in server logs. Decide which log shipper collects these entries, who can read them, and how long they are kept under your retention policy.
Prometheus or Grafana for job outcomes
A failed nightly job often goes unnoticed until a report is wrong. Export the status and timing of recent runs from cron.job_run_details through a PostgreSQL exporter or a custom query, then alert on failed runs and on jobs that have not run within their expected window. Agree on the owner and the response for each alert before go-live.
Backup and restore interactions
Restoring a database can restore cron.job definitions along with the data, so a restore may reactivate jobs that should stay off. Review scheduled jobs after every restore and during disaster recovery drills. Also confirm that the database that holds the job definitions is included in the backup set and that its restored schedule matches the intended state.
Airflow and other external schedulers
Jobs that span several systems, depend on external APIs or need retries with complex dependency graphs usually belong in an external scheduler such as Apache Airflow. Keep pg_cron for database-local work that must run beside the data. Confirm which system is the single source of truth for each job, so the same task is not triggered from both places.
How much pg_cron implementation costs and what the work needs from you
What drives the cost of a pg_cron implementation?
The cost follows the number and complexity of the jobs, not the extension itself, which is free to install. Cost rises with the number of jobs, how many databases they run in, whether jobs call stored procedures that need design work, how much existing cron or external scheduler logic must be mapped, and how much alerting and run history your operations team expects. Jobs that touch partitions, materialized views or retention rules need more review than simple vacuum or cleanup statements. Ask any partner to price the work from a written list of jobs, with each job's schedule, target database, owner and failure behavior, so the quote reflects what will actually be built.
Is pg_cron free, and what do I actually pay for?
The pg_cron extension is open source, so you pay for the work around it rather than a license. Typical one-time costs are design of the job catalog, extension installation and configuration on your servers, testing, and documentation. Recurring costs are the staff time to review job run history, the infrastructure that runs PostgreSQL, and any retainer you choose for upgrades and support. Confirm the license terms of the version you deploy with your legal team, and ask a partner to state in the quote which items are one-time and which recur.
Can our own database team implement pg_cron without a partner?
Yes, a team with PostgreSQL administration experience can install the extension, enable it through the server configuration, and schedule simple jobs on its own. The harder parts are working out which jobs belong in the database, granting the right roles, handling failures and monitoring. A team with no one who has run a background worker or reviewed job history in production will spend more time on those points. A useful self-check is whether someone on your team can explain where job definitions live, who can change them, and how a failed run gets noticed before deciding to build it yourselves.
What access and ownership does the client need to provide?
The work needs a named owner for the PostgreSQL clusters, an account with rights to change server configuration and restart the server in a maintenance window, and the ability to install the extension package on each host or container image. You also need a list of the jobs, the databases they run in and the people who depend on their output. Agree in writing who owns job definitions after handover, who approves changes to schedules and who receives failure alerts. Access should be granted to a test environment first, with production access limited to the agreed change window.
How do PostgreSQL upgrades affect the pg_cron extension?
The extension has to be installed for each PostgreSQL major version you run, and it must be rebuilt or replaced when the server is upgraded. Scheduled jobs live in the cron.job table, so that table and its history need to survive the upgrade method you choose. Plan the upgrade so the extension version matches the new server before the scheduler is re-enabled, and check that the background worker starts. Confirm the upgrade path with the pg_cron project and your packaging source before the maintenance window. The PostgreSQL upgrading documentation covers the main upgrade methods.
How are pg_cron jobs tested before they reach production?
Test each job against a copy of production data in a staging cluster with the same PostgreSQL major version and extension version. Check the cron syntax and time zone behavior, confirm the job runs in the intended database, and measure how long it takes and what locks it holds. Then test failure cases: a statement that errors, a job that overlaps with the next run, and a server restart during a run. Keep a rollback for each schedule change, and record which person approved each job before it is enabled in production.
What risks should we review before approving the scope?
The main risks are jobs that hold locks during business hours, overlapping runs that pile up, jobs that silently stop because nobody watches run history, and privileges that let a job change more data than intended. Ask the partner how the scope covers monitoring of run status, role separation for the account that owns jobs, and documented restart behavior. Confirm with your security team which logs must be kept and for how long, since job activity may fall under your audit requirements.
Keeping pg_cron working through PostgreSQL upgrades
pg_cron is part of the database cluster's state, so a PostgreSQL upgrade has to carry it across. The extension's background worker, its scheduling catalog and the cron.job table only exist on a cluster where the extension is installed and loaded through shared_preload_libraries. When you move to a new major version by pg_upgrade, logical replication or dump and restore, confirm that the new cluster has a pg_cron build compiled for that major version, that the library is listed in shared_preload_libraries, and that the extension is created in the postgres database where the scheduler lives. Check that the schedule definitions are restored and that the worker starts after the first restart. Confirm extension compatibility with each major version you target with the pg_cron project before you schedule the cutover, because the supported matrix is set by that project, not by PostgreSQL alone.
A minor update is a different operation. Per the PostgreSQL upgrading documentation, minor releases never change the internal storage format, so you replace the executables and restart the server. Your pg_cron build still has to match the server binary you install, so rebuild or update the package together with PostgreSQL rather than leaving an older library in place. Plan the restart window with the scheduled jobs in mind: a job that was running when the server stops will not resume on its own, and any job that writes in batches should be written to tolerate a rerun.
Use the support windows in the PostgreSQL versioning policy to decide when the upgrade is due. Major version 14 is supported until November 12, 2026, and 15 until November 11, 2027, so a cluster scheduling maintenance on 14 has a fixed end date to plan around. Test the full job list on a staging clone during the same window, including the cron.database_name and per-database jobs, and record the job count and last successful run before and after the cutover. Ask your extension vendor or packager to state in writing which pg_cron versions support each PostgreSQL major version you plan to run.
How DeployOpen scopes and delivers pg_cron implementation
DeployOpen plans, builds, documents and supports pg_cron for scheduled jobs inside PostgreSQL in infrastructure you control. We start from the jobs your database must run, the databases they touch and the people who will watch them, then agree the work in writing before any change is made.
How we scope
- We inventory the maintenance, partition rotation and refresh jobs you want to move into the database.
- The written scope names the PostgreSQL versions, databases and cron.job entries covered by the engagement.
- We agree which jobs stay with an external scheduler and record the reason for each choice.
How we build
- We install and configure the pg_cron extension and background worker on the PostgreSQL servers you specify.
- We test each job's cron syntax, timing and failure behavior in a non-production environment first.
- We set up run history checks and alerting so failed or overlapping job runs are visible to your team.
How we hand over
- You receive documentation of every scheduled job, its owner, its schedule and its recovery steps.
- We walk your database and operations staff through the job table, run history and retention settings.
- Runbooks cover adding, changing and disabling jobs, plus checks to run after a PostgreSQL minor or major upgrade.
How we support
- Ongoing support, upgrades and continuous testing are available as a retainer after handover.
- We can review the job inventory again when PostgreSQL versions change or new workloads need scheduling.
- Any change to the written scope is agreed in writing before work starts on it.

