H.4. pg_cron — cron-based job scheduler #
H.4.1. Description #
pg_cron is a simple cron-based job scheduler for Postgres Pro that runs inside the database as an extension.
The extension creates a background worker that tracks jobs in the
cron.job table.
Based on your configurations, to execute a job, the extension establishes a Postgres Pro connection or spawns a database worker.
pg_cron can run multiple jobs in parallel, but only one instance of each specific job at a time. If a second instance is triggered before the first finishes, it is queued and starts as soon as the first one completes.
H.4.2. Installation and Setup #
pg_cron is provided with
Postgres Pro Standard as a separate pre-built package
pg-cron-std-18 (for the detailed
installation instructions, see Chapter 16).
To start the pg_cron background worker, you
need to add pg_cron to the
shared_preload_libraries variable in the
postgresql.conf file.
shared_preload_libraries = 'pg_cron'
Note that pg_cron does not run any jobs as long as the server is in the hot standby mode, but it automatically starts when the server is promoted.
By default, the pg_cron background worker expects
its metadata tables to be created in the postgres database.
However, you can configure this by setting the
cron.database_name configuration parameter in
postgresql.conf.
cron.database_name = 'postgres'
pg_cron may only be installed to one database in a cluster. If you need to run jobs in multiple databases, use cron.schedule_in_database().
By default, pg_cron uses GMT time, but you can
adapt your time by setting cron.timezone in
postgresql.conf.
cron.timezone = 'PRC'
After restarting Postgres Pro, you can create the
pg_cron functions and metadata tables using
CREATE EXTENSION as follows:
-- Run as superuser CREATE EXTENSION pg_cron; -- Optionally, grant usage to regular users GRANT USAGE ON SCHEMA cron TO marco;
H.4.2.1. Ensuring pg_cron Can Start Jobs #
By default, pg_cron uses
libpq to open a new connection to the local
database, which needs to be allowed by
pg_hba.conf.
It may be necessary to enable trust
authentication for connections coming from localhost in for the
user running the cron job, or you can add the password to the
password file, which
libpq will use when opening a connection.
You can also use a Unix domain socket directory as the hostname
and enable trust authentication for local
connections in pg_hba.conf, which is normally safe:
# Connect via a Unix domain socket cron.host = '/tmp' # Can also be an empty string to look for the default directory cron.host = ''
Alternatively, pg_cron can be configured to use background workers. In that case, the number of concurrent jobs is limited by the max_worker_processes parameter, so you may need to raise that.
# Schedule jobs via background workers instead of localhost connections cron.use_background_workers = on # Increase the number of available background workers from the default of 8 max_worker_processes = 20
For security, jobs are executed in the database in which the
cron.schedule function is called with the
same permissions as the current user. In addition, users are
only able to see their own jobs in the
cron.job table.
-- View active jobs select * from cron.job;
H.4.3. Cron Syntax #
pg_cron uses the standard cron syntax.
┌───────────── minute (0 - 59) │ ┌────────────── hour (0 - 23) │ │ ┌─────────────── day of the month (1 - 31) or last day of the month ($) │ │ │ ┌──────────────── month (1 - 12) │ │ │ │ ┌───────────────── day of the week (0 - 6) (Sunday to Saturday; 7 is also Sunday; │ │ │ │ │ or use names;) │ │ │ │ │ │ │ │ │ │ * * * * *
pg_cron also allows you to:
Use
$to indicate the last day of the month.Use
[1-59] secondsto schedule a job based on an interval. Note that you cannot use seconds with other time units.
Examples of cron schedules:
'10 seconds' # every 10 seconds * * * * * # every minute */5 * * * * # every 5 minutes 0 * * * * # every hour 0 0 * * * # daily at 12AM 0 0 * * 1-5 # 12AM every weekday 0 1 * * 0 # 1AM every Sunday 0 13 2 6 * # 1PM on the 2nd of June
H.4.4. Managing and Creating Jobs #
Cron jobs can be managed by directly interacting with the
cron.job table if you have the required
permissions. However, it is recommended to use the cron functions listed
below.
Note
The row-level security policy
ensures that jobs can only be seen and modified by the user that created
them, unless the user is a superuser or has the BYPASSRLS
attribute.
-
cron.schedule(scheduletext,commandtext) returns bigint
cron.schedule(#job_nametext,scheduletext,commandtext) returns bigint Creates a cron job and returns a job ID.
This example creates an unnamed cron job that deletes old data on Saturday at 3:30AM (GMT):
SELECT cron.schedule( '30 3 * * 6', $$DELETE FROM events WHERE event_time < now() - interval '1 week'$$ );This example creates a named cron job that performs vacuum every day at 10:00AM (GMT):
SELECT cron.schedule( 'nightly-vacuum', '0 10 * * *', 'VACUUM' );This example creates a named job that runs every 30 seconds:
SELECT cron.schedule( 'run_every_30_seconds', '30 seconds', 'SELECT 1' );This example creates a job that calls a stored procedure every 5 seconds:
SELECT cron.schedule( 'process-updates', '5 seconds', 'CALL process_updates()' );This example creates a job that processes payroll at 12:00AM of the last day of each month:
SELECT cron.schedule( 'process-payroll', '0 12 $ * *', 'CALL process_payroll()' );-
cron.schedule_in_database(#job_nametext,scheduletext,commandtext,databasetext,usernametextDEFAULT NULL,activebooleanDEFAULT true) returns bigint Creates a cron job in the specified database and returns a job ID.
This example creates a job that deletes old data on Saturday at 3:30AM (GMT):
SELECT cron.schedule_in_database( 'delete_old_data', '30 3 * * 6', $$DELETE FROM events WHERE event_time < now() - interval '1 week'$$, 'some_other_database' );-
cron.unschedule(job_nametext) returns boolean
cron.unschedule(#job_idbigint) returns boolean Removes a cron job with the specified name or ID. Returns
trueif the job was removed successfully.This example removes the job by its name:
SELECT cron.unschedule('nightly-vacuum');This example removes the job by its ID:
SELECT cron.unschedule(42);
-
cron.alter_job(#job_idbigint,scheduletextDEFAULT NULL,commandtextDEFAULT NULL,databasetextDEFAULT NULL,usernametextDEFAULT NULL,activebooleanDEFAULT true) returns void Changes parameters of the specified cron job.
This example changes the job schedule:
SELECT cron.alter_job(42, '0 10 * * *');
This example changes the job schedule, command, and username:
SELECT cron.alter_job( 42, '0 10 * * *', 'VACUUM', username := 'some_other_user' );This example deactivates a job:
SELECT cron.alter_job(42, active := false);
H.4.5. Configuration Parameters #
The pg_cron extension supports the configuration parameters listed below.
-
cron.database_name# Specifies the database in which the pg_cron background worker should run. The default value is
postgres.-
cron.enable_superuser_jobs# Allows jobs to be scheduled as superusers. The default value is
on.-
cron.host# Specifies the hostname to connect to
postgres. The default value islocalhost.-
cron.launch_active_jobs# When
off, disables all active jobs without requiring a server restart. The default value ison.-
cron.log_min_messages# Specifies the minimum level of messages for the launcher background worker. The default value is
WARNING.-
cron.log_run# Specifies whether to log all run details in the cron.job_run_details table. The default value is
on.-
cron.log_statement# Specifies whether to log all cron statements prior to execution. The default value is
on.-
cron.max_running_jobs# Specifies the maximum number of jobs that can be running at the same time. The default value is
32.-
cron.timezone# Specifies the timezone in which the pg_cron background worker should run. The default value is
GMT.-
cron.use_background_workers# Specifies whether to use background workers instead of client connections. The default value is
off.
H.4.5.1. Changing Configuration Parameters #
To view parameter configurations, run:
SELECT * FROM pg_settings WHERE name LIKE 'cron.%';
Parameters can be changed in the postgresql.conf
file or with the following command:
ALTER SYSTEM SET cron.<parameter> TO '<value>';
The cron.log_min_messages and
cron.launch_active_jobs parameters have a pg_settings.context set to
sighup. They can be
finalized by executing
SELECT pg_reload_conf();.
All the other settings have the postmaster context
and only take effect after a server restart.
H.4.6. Monitoring Jobs #
H.4.6.1. Reviewing the cron.job_run_details table #
You can view job activity in the cron.job_run_details
table:
SELECT * FROM cron.job_run_details ORDER BY start_time DESC LIMIT 5; ┌───────┬───────┬─────────┬──────────┬──────────┬───────────────────┬───────────┬──────────────────┬───────────────────────────────┬───────────────────────────────┐ │ jobid │ runid │ job_pid │ database │ username │ command │ status │ return_message │ start_time │ end_time │ ├───────┼───────┼─────────┼──────────┼──────────┼───────────────────┼───────────┼──────────────────┼───────────────────────────────┼───────────────────────────────┤ │ 11 │ 4328 │ 2610 │ postgres │ marco │ select pg_sleep(3)│ running │ NULL │ 2023-02-07 09:30:00.098164+01 │ NULL │ │ 10 │ 4327 │ 2609 │ postgres │ marco │ select process() │ succeeded │ SELECT 1 │ 2023-02-07 09:29:00.015168+01 │ 2023-02-07 09:29:00.832308+01 │ │ 10 │ 4321 │ 2603 │ postgres │ marco │ select process() │ succeeded │ SELECT 1 │ 2023-02-07 09:28:00.011965+01 │ 2023-02-07 09:28:01.420901+01 │ │ 10 │ 4320 │ 2602 │ postgres │ marco │ select process() │ failed │ server restarted │ 2023-02-07 09:27:00.011833+01 │ 2023-02-07 09:27:00.72121+01 │ │ 9 │ 4320 │ 2602 │ postgres │ marco │ select do_stuff() │ failed │ job canceled │ 2023-02-07 09:26:00.011833+01 │ 2023-02-07 09:26:00.22121+01 │ └───────┴───────┴─────────┴──────────┴──────────┴───────────────────┴───────────┴──────────────────┴───────────────────────────────┴───────────────────────────────┘ (10 rows)
The records in the table are not cleaned automatically, but
every user that can schedule cron jobs also has permission to
delete their own cron.job_run_details
records.
Especially when you have jobs that run every few seconds, it can be a good idea to clean up regularly, which can easily be done using pg_cron itself.
-- Delete old cron.job_run_details records of the current user every day at noon
SELECT cron.schedule('delete-job-run-details', '0 12 * * *', $$DELETE FROM cron.job_run_details WHERE end_time < now() - interval '7 days'$$);
If you do not want to use
cron.job_run_details at all, then you can add
cron.log_run = off to postgresql.conf.
H.4.6.2. Logging Parameters #
If the cron.log_statement parameter is configured, jobs are logged before execution. The cron.log_min_messages parameter controls the minimum level of messages that will be recorded.