### Example postgresql.conf Configuration Source: https://context7.com/citusdata/pg_cron/llms.txt An example `postgresql.conf` file showing common pg_cron settings. Ensure `shared_preload_libraries` includes `pg_cron`. ```ini # postgresql.conf — complete example configuration shared_preload_libraries = 'pg_cron' cron.database_name = 'app_production' cron.timezone = 'UTC' cron.host = '/var/run/postgresql' # unix socket cron.max_running_jobs = 16 cron.use_background_workers = on cron.log_run = on cron.log_statement = off cron.log_min_messages = WARNING cron.enable_superuser_jobs = off ``` -------------------------------- ### Build pg_cron from Source Source: https://github.com/citusdata/pg_cron/blob/main/README.md Compile and install pg_cron from its source code. Ensure `pg_config` is in your PATH and that you have the necessary build tools installed. This process involves cloning the repository, configuring, and installing. ```bash git clone https://github.com/citusdata/pg_cron.git cd pg_cron # Ensure pg_config is in your path, e.g. export PATH=/usr/pgsql-18/bin:$PATH make && sudo PATH=$PATH make install ``` -------------------------------- ### Install pg_cron Package Source: https://context7.com/citusdata/pg_cron/llms.txt Install the pg_cron package using system package managers or build from source. ```bash # Red Hat / CentOS / Amazon Linux sudo yum install -y pg_cron_18 # Debian / Ubuntu sudo apt-get -y install postgresql-18-cron # Build from source git clone https://github.com/citusdata/pg_cron.git cd pg_cron export PATH=/usr/pgsql-18/bin:$PATH make && sudo PATH=$PATH make install ``` -------------------------------- ### Install pg_cron on Debian/Ubuntu Source: https://github.com/citusdata/pg_cron/blob/main/README.md Install the pg_cron extension on Debian-based systems using `apt-get`. This command installs the extension package for PostgreSQL 18. ```bash # Install the pg_cron extension sudo apt-get -y install postgresql-18-cron ``` -------------------------------- ### Create pg_cron Extension and Grant Usage Source: https://github.com/citusdata/pg_cron/blob/main/README.md After configuring PostgreSQL and restarting the server, run `CREATE EXTENSION pg_cron;` as a superuser to install the extension's functions and metadata tables. Optionally, grant usage of the `cron` schema to regular users. ```sql -- run as superuser: CREATE EXTENSION pg_cron; -- optionally, grant usage to regular users: GRANT USAGE ON SCHEMA cron TO marco; ``` -------------------------------- ### Example Cron Schedules Source: https://github.com/citusdata/pg_cron/blob/main/README.md Provides various examples of cron schedules, including intervals in seconds, every minute, every 5 minutes, daily, weekly, and specific dates. ```text '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 ``` -------------------------------- ### Schedule Cron Job Examples Source: https://context7.com/citusdata/pg_cron/llms.txt Examples of scheduling jobs using the cron.schedule function with different time intervals and commands. Ensure the 'cron' schema is available and the function is accessible. ```sql SELECT cron.schedule('every-10-sec', '10 seconds', 'SELECT 1'); ``` ```sql SELECT cron.schedule('every-minute', '* * * * *', 'SELECT 1'); ``` ```sql SELECT cron.schedule('every-5-min', '*/5 * * * *', 'CALL refresh()'); ``` ```sql SELECT cron.schedule('hourly', '0 * * * *', 'CALL hourly_task()'); ``` ```sql SELECT cron.schedule('daily-midnight', '0 0 * * *', 'CALL daily_cleanup()'); ``` ```sql SELECT cron.schedule('weekdays-only', '0 0 * * 1-5', 'CALL weekday_job()'); ``` ```sql SELECT cron.schedule('sunday-1am', '0 1 * * 0', 'CALL weekly_report()'); ``` ```sql SELECT cron.schedule('june-2nd-1pm', '0 13 2 6 *', 'CALL june_special()'); ``` ```sql SELECT cron.schedule('last-day-noon', '0 12 $ * *', 'CALL month_end_close()'); ``` -------------------------------- ### Install pg_cron on Red Hat/CentOS/Fedora/Amazon Linux Source: https://github.com/citusdata/pg_cron/blob/main/README.md Install the pg_cron extension on Red Hat-based systems using `yum`. This command installs the extension package for PostgreSQL 18. ```bash # Install the pg_cron extension sudo yum install -y pg_cron_18 ``` -------------------------------- ### Configure pg_cron Shared Preload Libraries Source: https://github.com/citusdata/pg_cron/blob/main/README.md Add `pg_cron` to the `shared_preload_libraries` setting in `postgresql.conf` to enable the pg_cron background worker on server startup. Note that pg_cron does not run jobs in hot standby mode but will start automatically upon promotion. ```ini # add to postgresql.conf # required to load pg_cron background worker on start-up shared_preload_libraries = 'pg_cron' ``` -------------------------------- ### Cron Schedule Syntax Source: https://github.com/citusdata/pg_cron/blob/main/README.md Illustrates the standard cron syntax for defining job schedules, including minutes, hours, day of month, month, and day of week. ```text ┌───────────── min (0 - 59) │ ┌────────────── hour (0 - 23) │ │ ┌─────────────── day of month (1 - 31) or last day of the month ($) │ │ │ ┌──────────────── month (1 - 12) │ │ │ │ ┌───────────────── day of week (0 - 6) (0 to 6 are Sunday to │ │ │ │ │ Saturday, or use names; 7 is also Sunday) │ │ │ │ │ │ │ │ │ │ * * * * * ``` -------------------------------- ### View pg_cron Extension Settings Source: https://github.com/citusdata/pg_cron/blob/main/README.md Retrieve all configuration settings related to the pg_cron extension from the `pg_settings` catalog. ```sql SELECT * FROM pg_settings WHERE name LIKE 'cron.%'; ``` -------------------------------- ### Configure pg_cron in postgresql.conf Source: https://context7.com/citusdata/pg_cron/llms.txt Configure pg_cron by adding it to shared_preload_libraries and optionally setting cron.database_name, cron.timezone, cron.host, and cron.use_background_workers. ```ini # postgresql.conf — required settings shared_preload_libraries = 'pg_cron' # Optional: change the metadata database (default: postgres) cron.database_name = 'postgres' # Optional: set a local timezone for schedule evaluation (default: GMT) cron.timezone = 'America/New_York' # Optional: connect via unix socket instead of TCP cron.host = '/var/run/postgresql' # Optional: use background workers instead of libpq connections cron.use_background_workers = on max_worker_processes = 20 ``` -------------------------------- ### Create a Cron Job Source: https://github.com/citusdata/pg_cron/blob/main/README.md Schedules a new cron job with a specified schedule and SQL command. Returns the job ID upon successful creation. Use this for jobs running in the current database. ```sql -- Delete old data on Saturday at 3:30am (GMT) SELECT cron.schedule( '30 3 * * 6', $$DELETE FROM events WHERE event_time < now() - interval '1 week'$$ ``` ```sql -- run SELECT 1 every 30 seconds SELECT cron.schedule( 'run_every_30_seconds', '30 seconds', 'SELECT 1' ``` ```sql -- Call a stored procedure every 5 seconds SELECT cron.schedule( 'process-updates', '5 seconds', 'CALL process_updates()' ``` ```sql -- Process payroll at 12:00 of the last day of each month SELECT cron.schedule( 'process-payroll', '0 12 $ * *', 'CALL process_payroll()' ``` -------------------------------- ### View pg_cron Configuration Settings Source: https://context7.com/citusdata/pg_cron/llms.txt Query `pg_settings` to view all current pg_cron GUC parameters. Some settings require a server restart, while others take effect after `pg_reload_conf()`. ```sql -- View all current pg_cron settings SELECT name, setting, unit, short_desc FROM pg_settings WHERE name LIKE 'cron.%' ORDER BY name; ``` -------------------------------- ### Configuration Settings Source: https://context7.com/citusdata/pg_cron/llms.txt Details on how to view and modify pg_cron configuration parameters (GUCs) using `postgresql.conf` or `ALTER SYSTEM`. ```APIDOC ## Configuration Settings All pg_cron GUC parameters live in `postgresql.conf` (or set via `ALTER SYSTEM`). Most require a server restart; `cron.log_min_messages` and `cron.launch_active_jobs` take effect after `SELECT pg_reload_conf()`. ### View all current pg_cron settings ```sql SELECT name, setting, unit, short_desc FROM pg_settings WHERE name LIKE 'cron.%' ORDER BY name; ``` **Example Output:** ```ini -- name | setting | description -- ----------------------------+-----------+------------------------------------------- -- cron.database_name | postgres | Database for pg_cron background worker -- cron.enable_superuser_jobs | on | Allow superuser jobs -- cron.host | localhost | Hostname for postgres connections -- cron.launch_active_jobs | on | Master on/off switch (sighup) -- cron.log_min_messages | WARNING | Log level for launcher worker (sighup) -- cron.log_run | on | Write to cron.job_run_details -- cron.log_statement | on | Log SQL before execution -- cron.max_running_jobs | 32 | Max parallel job instances -- cron.timezone | GMT | Timezone for schedule evaluation -- cron.use_background_workers | off | Use bgworkers instead of connections ``` ### `postgresql.conf` Example ```ini # postgresql.conf — complete example configuration shared_preload_libraries = 'pg_cron' cron.database_name = 'app_production' cron.timezone = 'UTC' cron.host = '/var/run/postgresql' # unix socket cron.max_running_jobs = 16 cron.use_background_workers = on cron.log_run = on cron.log_statement = off cron.log_min_messages = WARNING cron.enable_superuser_jobs = off ``` ### Change a sighup-context setting without restarting ```sql ALTER SYSTEM SET cron.launch_active_jobs TO 'off'; SELECT pg_reload_conf(); ``` ### Temporarily pause all jobs (useful during maintenance windows) ```sql ALTER SYSTEM SET cron.launch_active_jobs TO 'off'; SELECT pg_reload_conf(); -- ... perform maintenance ... ALTER SYSTEM SET cron.launch_active_jobs TO 'on'; SELECT pg_reload_conf(); ``` ``` -------------------------------- ### Create pg_cron Extension Source: https://context7.com/citusdata/pg_cron/llms.txt Create the pg_cron extension in the target database as a superuser after restarting PostgreSQL. Grant non-superusers usage on the cron schema. ```sql -- Run as superuser after restarting PostgreSQL CREATE EXTENSION pg_cron; -- Grant non-superusers the ability to schedule jobs GRANT USAGE ON SCHEMA cron TO app_user; ``` -------------------------------- ### Monitor Job Execution with cron.job_run_details Source: https://context7.com/citusdata/pg_cron/llms.txt Query the `cron.job_run_details` table to monitor job outcomes, alert on failures, and debug performance. It records the status, return message, and timing of each job execution. ```sql -- Recent execution history with duration SELECT j.jobname, r.runid, r.status, r.return_message, r.start_time, r.end_time, round(extract(epoch FROM (r.end_time - r.start_time))::numeric, 3) AS seconds FROM cron.job_run_details r JOIN cron.job j USING (jobid) ORDER BY r.start_time DESC LIMIT 20; ``` ```sql -- Find all failed runs in the last 24 hours SELECT jobid, runid, command, return_message, start_time FROM cron.job_run_details WHERE status = 'failed' AND start_time > now() - interval '24 hours' ORDER BY start_time DESC; ``` ```sql -- Currently running jobs SELECT jobid, runid, job_pid, command, start_time, now() - start_time AS running_for FROM cron.job_run_details WHERE status = 'running'; ``` ```sql -- Automatically purge run details older than 7 days (scheduled via pg_cron itself) SELECT cron.schedule( 'purge-job-run-details', '0 12 * * *', $$DELETE FROM cron.job_run_details WHERE end_time < now() - interval '7 days'$$ ); ``` -------------------------------- ### Schedule a Job in a Different Database with cron.schedule_in_database Source: https://context7.com/citusdata/pg_cron/llms.txt Schedules a job to run in a specified database within the same cluster. Requires superuser privileges or an explicit EXECUTE grant. Optionally specify the username and whether the job should be active by default. ```sql SELECT cron.schedule_in_database( 'analytics-purge', '0 1 * * 0', $$DELETE FROM audit_log WHERE created_at < now() - interval '90 days'$$, 'analytics' ``` ```sql SELECT cron.schedule_in_database( 'reporting-rollup', '0 6 * * *', 'CALL generate_daily_report()', 'reporting_db', 'report_runner' ``` ```sql SELECT cron.schedule_in_database( 'pending-migration', '0 3 * * *', 'CALL run_migration()', 'app_db', active := false ); ``` -------------------------------- ### Schedule a SQL Command with cron.schedule Source: https://context7.com/citusdata/pg_cron/llms.txt Schedules a SQL command to run on a cron schedule. Use named jobs for easier management with `cron.unschedule` and `cron.alter_job`. Supports standard cron syntax and sub-minute intervals like '10 seconds'. ```sql SELECT cron.schedule('* * * * *', 'SELECT 1'); ``` ```sql SELECT cron.schedule('heartbeat', '10 seconds', 'SELECT pg_sleep(0)'); ``` ```sql SELECT cron.schedule('*/5 * * * *', 'CALL refresh_summary_table()'); ``` ```sql SELECT cron.schedule('nightly-vacuum', '0 2 * * *', 'VACUUM ANALYZE events'); ``` ```sql SELECT cron.schedule( 'purge-old-events', '30 3 * * 6', $$DELETE FROM events WHERE event_time < now() - interval '30 days'$$ ``` ```sql SELECT cron.schedule( 'process-payroll', '0 12 $ * *', 'CALL process_payroll()' ``` ```sql SELECT cron.schedule( 'process-updates', '5 seconds', 'CALL process_updates()' ``` ```sql SELECT jobid, jobname, schedule, command, active FROM cron.job WHERE jobname = 'nightly-vacuum'; ``` -------------------------------- ### cron.job_run_details Table Definition and Query Source: https://context7.com/citusdata/pg_cron/llms.txt The cron.job_run_details table logs job executions. Users can query their own execution history. ```sql -- Full table definition (added in v1.3) CREATE TABLE cron.job_run_details ( jobid bigint, runid bigint PRIMARY KEY DEFAULT nextval('cron.runid_seq'), job_pid integer, database text, username text, command text, status text, -- 'running' | 'succeeded' | 'failed' return_message text, start_time timestamptz, end_time timestamptz ); -- Check the last 10 executions of all your jobs SELECT jobid, runid, command, status, return_message, start_time, end_time, extract(epoch FROM (end_time - start_time)) AS duration_sec FROM cron.job_run_details ORDER BY start_time DESC LIMIT 10; ``` -------------------------------- ### Create a Named Cron Job Source: https://github.com/citusdata/pg_cron/blob/main/README.md Schedules a new cron job with a specific name, schedule, and SQL command. Returns the job ID. Useful for identifying and managing jobs by name. ```sql -- Vacuum every day at 10:00am (GMT) SELECT cron.schedule( 'nightly-vacuum', '0 10 * * *', 'VACUUM' ``` -------------------------------- ### Configure pg_cron Hostname Source: https://github.com/citusdata/pg_cron/blob/main/README.md Set the hostname for pg_cron to connect to PostgreSQL. Can be a traditional hostname or an empty string to use the default Unix domain socket directory. ```sql # Connect via a unix domain socket: cron.host = '/tmp' # Can also be an empty string to look for the default directory: cron.host = '' ``` -------------------------------- ### Define cron.job Table Structure Source: https://github.com/citusdata/pg_cron/blob/main/README.md This SQL defines the schema for the cron.job table, which stores job configurations including schedule, command, and execution details. ```sql CREATE TABLE cron.job ( jobid bigint primary key default pg_catalog.nextval('cron.jobid_seq'), schedule text not null, command text not null, nodename text not null default 'localhost', nodeport int not null default pg_catalog.inet_server_port(), database text not null default pg_catalog.current_database(), username text not null default current_user ); ``` -------------------------------- ### cron.schedule Source: https://context7.com/citusdata/pg_cron/llms.txt Schedules a SQL command to run on a cron schedule. It can be called with two arguments for an anonymous job or three arguments for a named job. Named jobs can be referenced later for removal or alteration. ```APIDOC ## `cron.schedule` — Schedule a Job Schedules a SQL command to run on a cron schedule. Returns the integer `jobid`. Can be called with two arguments (anonymous job) or three arguments (named job). Named jobs can later be referenced by name in `cron.unschedule` and `cron.alter_job`. ### Signature (anonymous) `cron.schedule(schedule text, command text) RETURNS bigint` ### Signature (named) `cron.schedule(job_name text, schedule text, command text) RETURNS bigint` ### Examples Every minute: ```sql SELECT cron.schedule('* * * * *', 'SELECT 1'); ``` Every 10 seconds (sub-minute interval): ```sql SELECT cron.schedule('heartbeat', '10 seconds', 'SELECT pg_sleep(0)'); ``` Every 5 minutes: ```sql SELECT cron.schedule('*/5 * * * *', 'CALL refresh_summary_table()'); ``` Daily vacuum at 2:00 AM GMT: ```sql SELECT cron.schedule('nightly-vacuum', '0 2 * * *', 'VACUUM ANALYZE events'); ``` Delete rows older than 30 days every Saturday at 3:30 AM: ```sql SELECT cron.schedule( 'purge-old-events', '30 3 * * 6', $$DELETE FROM events WHERE event_time < now() - interval '30 days'$$ ); -- returns: 7 (the assigned jobid) ``` Run payroll procedure on the last day of each month at noon: ```sql SELECT cron.schedule( 'process-payroll', '0 12 $ * *', 'CALL process_payroll()' ); ``` Call a stored procedure every 5 seconds: ```sql SELECT cron.schedule( 'process-updates', '5 seconds', 'CALL process_updates()' ); ``` Verify the job was registered: ```sql SELECT jobid, jobname, schedule, command, active FROM cron.job WHERE jobname = 'nightly-vacuum'; ``` ``` -------------------------------- ### Review cron job activity Source: https://github.com/citusdata/pg_cron/blob/main/README.md View recent job activity by querying the `cron.job_run_details` table. This table stores records of job executions, including status, messages, and timestamps. ```sql select * from cron.job_run_details order by start_time desc limit 5; ``` -------------------------------- ### Dynamically Change Configuration Settings Source: https://context7.com/citusdata/pg_cron/llms.txt Modify pg_cron settings like `cron.launch_active_jobs` without restarting the server using `ALTER SYSTEM` and `pg_reload_conf()`. This is useful for temporary changes during maintenance. ```sql -- Change a sighup-context setting without restarting ALTER SYSTEM SET cron.launch_active_jobs TO 'off'; SELECT pg_reload_conf(); ``` ```sql -- Temporarily pause all jobs (useful during maintenance windows) ALTER SYSTEM SET cron.launch_active_jobs TO 'off'; SELECT pg_reload_conf(); -- ... perform maintenance ... ALTER SYSTEM SET cron.launch_active_jobs TO 'on'; SELECT pg_reload_conf(); ``` -------------------------------- ### View Active pg_cron Jobs Source: https://github.com/citusdata/pg_cron/blob/main/README.md Query the `cron.job` table to view all currently scheduled and active jobs managed by pg_cron. ```sql -- View active jobs select * from cron.job; ``` -------------------------------- ### Configure pg_cron Database Name Source: https://github.com/citusdata/pg_cron/blob/main/README.md Set the `cron.database_name` parameter in `postgresql.conf` to specify the database where pg_cron should store its metadata. By default, it uses the 'postgres' database. ```ini # add to postgresql.conf # optionally, specify the database in which the pg_cron background worker should run (defaults to postgres) cron.database_name = 'postgres' ``` -------------------------------- ### cron.job_run_details Table Source: https://context7.com/citusdata/pg_cron/llms.txt The `cron.job_run_details` table records the outcome of every job execution, providing data for operational monitoring, alerting on failures, and debugging. ```APIDOC ## Monitoring — `cron.job_run_details` The `cron.job_run_details` table records the outcome of every job execution. It supports operational monitoring, alerting on failures, and debugging slow or crashing jobs. ### Query Examples Recent execution history with duration: ```sql SELECT j.jobname, r.runid, r.status, r.return_message, r.start_time, r.end_time, round(extract(epoch FROM (r.end_time - r.start_time))::numeric, 3) AS seconds FROM cron.job_run_details r JOIN cron.job j USING (jobid) ORDER BY r.start_time DESC LIMIT 20; ``` Find all failed runs in the last 24 hours: ```sql SELECT jobid, runid, command, return_message, start_time FROM cron.job_run_details WHERE status = 'failed' AND start_time > now() - interval '24 hours' ORDER BY start_time DESC; ``` Currently running jobs: ```sql SELECT jobid, runid, job_pid, command, start_time, now() - start_time AS running_for FROM cron.job_run_details WHERE status = 'running'; ``` Automatically purge run details older than 7 days (scheduled via pg_cron itself): ```sql SELECT cron.schedule( 'purge-job-run-details', '0 12 * * *', $$DELETE FROM cron.job_run_details WHERE end_time < now() - interval '7 days'$$ ); ``` ``` -------------------------------- ### Schedule a Cron Job in a Specific Database Source: https://github.com/citusdata/pg_cron/blob/main/README.md Allows scheduling a cron job with a specific name, schedule, command, and target database. Optionally, a username and active status can be provided. Returns the job ID upon successful creation. ```APIDOC ## cron.schedule_in_database ### Description Creates a cron job with a specified name, schedule, command, and database. Optionally accepts a username and an active status. Returns the job ID. ### Signature ```sql CREATE OR REPLACE FUNCTION cron.schedule_in_database( job_name text, schedule text, command text, database text, username text DEFAULT NULL::text, active boolean DEFAULT true ) RETURNS bigint ``` ### Parameters - **job_name** (text) - Required - The name of the cron job. - **schedule** (text) - Required - The cron schedule string (e.g., '30 3 * * *'). - **command** (text) - Required - The SQL command to execute. - **database** (text) - Required - The database in which to run the command. - **username** (text) - Optional - The database user to run the command as. - **active** (boolean) - Optional - Whether the job should be active (default: true). ### Example ```sql -- Create a cron job in 'some_other_database' SELECT cron.schedule_in_database( 'delete_old_data', '30 3 * * 6', $$DELETE FROM events WHERE event_time < now() - interval '1 week'$$, 'some_other_database' ); -- returns cron id ``` ``` -------------------------------- ### Schedule cleanup of old job run details Source: https://github.com/citusdata/pg_cron/blob/main/README.md Schedule a daily job to delete old records from `cron.job_run_details` that are older than 7 days. This helps manage table size, especially for frequently running jobs. The job runs at noon daily. ```sql -- 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'$$); ``` -------------------------------- ### Cron Schedule Format Source: https://context7.com/citusdata/pg_cron/llms.txt The cron schedule format consists of five fields: minute, hour, day of month, month, and day of week. An asterisk (*) denotes all possible values for a field. ```text ┌───────────── min (0–59) │ ┌────────────── hour (0–23) │ │ ┌─────────────── day of month (1–31, or $ = last day) │ │ │ ┌──────────────── month (1–12) │ │ │ │ ┌───────────────── day of week (0–6, 0 = Sunday; 7 also = Sunday) │ │ │ │ │ * * * * * ``` -------------------------------- ### Configure pg_cron Background Workers Source: https://github.com/citusdata/pg_cron/blob/main/README.md Enable pg_cron to use background workers for job execution and increase the maximum number of worker processes to accommodate more concurrent jobs. ```sql # 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 ``` -------------------------------- ### cron.job Table Definition and Query Source: https://context7.com/citusdata/pg_cron/llms.txt The cron.job table stores scheduled jobs. Users can view their own jobs using the provided SELECT statement. ```sql -- Full table definition CREATE TABLE cron.job ( jobid bigint PRIMARY KEY DEFAULT nextval('cron.jobid_seq'), schedule text NOT NULL, -- cron expression or 'N seconds' command text NOT NULL, -- SQL statement to execute nodename text NOT NULL DEFAULT 'localhost', nodeport int NOT NULL DEFAULT inet_server_port(), database text NOT NULL DEFAULT current_database(), username text NOT NULL DEFAULT current_user, active boolean NOT NULL DEFAULT true, -- enable/disable without deleting jobname text -- optional unique name per user ); -- RLS: users can only see/modify their own rows -- (superusers and bypassrls users see all rows) -- View your own scheduled jobs SELECT jobid, schedule, command, active, jobname FROM cron.job ORDER BY jobid; ``` -------------------------------- ### cron.schedule Source: https://github.com/citusdata/pg_cron/blob/main/README.md Schedules a new cron job. It can optionally take a job name as the first argument. Returns the job ID of the created job. ```APIDOC ## cron.schedule ### Description Schedules a new cron job. It can optionally take a job name as the first argument. Returns the job ID of the created job. ### Method SQL Function ### Signatures ```sql -- create job, return jobid CREATE OR REPLACE FUNCTION cron.schedule(schedule text, command text) RETURNS bigint; -- create named job, return jobid CREATE OR REPLACE FUNCTION cron.schedule(job_name text, schedule text, command text) RETURNS bigint ``` ### Parameters #### Function Parameters - **schedule** (text) - Required - The cron schedule string. - **command** (text) - Required - The SQL command or function call to execute. - **job_name** (text) - Optional - A unique name for the cron job. ### Examples #### Create a cron job ```sql -- Delete old data on Saturday at 3:30am (GMT) SELECT cron.schedule( '30 3 * * 6', $$DELETE FROM events WHERE event_time < now() - interval '1 week'$$ ); -- returns cron id ``` #### Create a named cron job ```sql -- Vacuum every day at 10:00am (GMT) SELECT cron.schedule( 'nightly-vacuum', '0 10 * * *', 'VACUUM' ); -- returns cron id ``` #### Create a job that runs every 30 seconds ```sql -- run SELECT 1 every 30 seconds SELECT cron.schedule( 'run_every_30_seconds', '30 seconds', 'SELECT 1' ); -- returns cron id ``` #### Create a job that calls a stored procedure every 5 seconds ```sql -- Call a stored procedure every 5 seconds SELECT cron.schedule( 'process-updates', '5 seconds', 'CALL process_updates()' ); -- returns cron id ``` #### Create a job that processes payroll at 12:00 of the last day of each month ```sql -- Process payroll at 12:00 of the last day of each month SELECT cron.schedule( 'process-payroll', '0 12 $ * *', 'CALL process_payroll()' ); -- returns cron id ``` ``` -------------------------------- ### cron.schedule_in_database Source: https://context7.com/citusdata/pg_cron/llms.txt Schedules a job to run in a specified database, different from the one where the job is stored. This function requires superuser privileges or explicit EXECUTE grant and is useful for managing jobs across multiple databases within the same cluster. ```APIDOC ## `cron.schedule_in_database` — Schedule a Job in a Different Database Schedules a job that runs in a database other than the one where `cron.job` is stored. Requires superuser or explicit EXECUTE grant. Useful when a single pg_cron installation manages jobs across multiple databases in the same cluster. ### Signature `cron.schedule_in_database( job_name text, schedule text, command text, database text, username text DEFAULT NULL, -- defaults to current_user active boolean DEFAULT true ) RETURNS bigint` ### Examples Purge old audit records in the 'analytics' database every Sunday at 1 AM: ```sql SELECT cron.schedule_in_database( 'analytics-purge', '0 1 * * 0', $$DELETE FROM audit_log WHERE created_at < now() - interval '90 days'$$, 'analytics' ); -- returns: 12 ``` Run a procedure as a specific user in a specific database: ```sql SELECT cron.schedule_in_database( 'reporting-rollup', '0 6 * * *', 'CALL generate_daily_report()', 'reporting_db', 'report_runner' ); ``` Schedule but start inactive (won't run until activated): ```sql SELECT cron.schedule_in_database( 'pending-migration', '0 3 * * *', 'CALL run_migration()', 'app_db', active := false ); ``` ``` -------------------------------- ### Schedule a Cron Job in a Specific Database Source: https://github.com/citusdata/pg_cron/blob/main/README.md Use `cron.schedule_in_database` to create a new cron job that runs in a specified database. This is useful when you need to manage jobs across different databases within a PostgreSQL cluster. The function returns the job ID upon successful creation. ```sql -- create job, return jobid CREATE OR REPLACE FUNCTION cron.schedule_in_database( job_name text, schedule text, command text, database text, username text DEFAULT NULL::text, active boolean DEFAULT true ) RETURNS bigint ``` ```sql -- Delete 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' ); -- returns cron id ``` -------------------------------- ### Configure pg_cron Timezone Source: https://github.com/citusdata/pg_cron/blob/main/README.md Set the `cron.timezone` parameter in `postgresql.conf` to specify the timezone for job execution. This allows jobs to run according to a local timezone rather than defaulting to GMT. ```ini # add to postgresql.conf # optionally, specify the timezone in which the pg_cron background worker should run (defaults to GMT). E.g: cron.timezone = 'PRC' ``` -------------------------------- ### Alter a Cron Job's Schedule, Command, and Username Source: https://github.com/citusdata/pg_cron/blob/main/README.md Update multiple properties of a cron job, including its schedule, command, and the username under which it runs, using `cron.alter_job`. Ensure the `username` parameter is correctly specified using the `:=` operator. ```sql -- change job's command SELECT cron.alter_job( 42, '0 10 * * *', 'VACUUM', username := 'some_other_user' ); -- returns void ``` -------------------------------- ### Modify an Existing Job with cron.alter_job Source: https://context7.com/citusdata/pg_cron/llms.txt Use `cron.alter_job` to update properties of an existing job. Only non-NULL arguments are applied. This is useful for enabling/disabling or changing schedules without re-creation. ```sql -- Signature cron.alter_job( job_id bigint, schedule text DEFAULT NULL, command text DEFAULT NULL, database text DEFAULT NULL, username text DEFAULT NULL, active boolean DEFAULT NULL ) RETURNS void ``` ```sql -- Change only the schedule of job 7 SELECT cron.alter_job(7, '0 3 * * *'); ``` ```sql -- Change schedule and command together SELECT cron.alter_job( 7, '0 3 * * 1-5', 'VACUUM ANALYZE orders, customers' ); ``` ```sql -- Change only the executing username (named parameter style) SELECT cron.alter_job(7, username := 'maintenance_user'); ``` ```sql -- Disable a job without deleting it (can be re-enabled later) SELECT cron.alter_job(7, active := false); ``` ```sql -- Re-enable a previously disabled job SELECT cron.alter_job(7, active := true); ``` ```sql -- Move a job to run in a different database SELECT cron.alter_job(7, database := 'new_app_db'); ``` ```sql -- Full update: reschedule, new command, new user, re-enable SELECT cron.alter_job( 7, '30 1 * * *', 'CALL full_maintenance()', 'app_db', 'admin', true ); ``` -------------------------------- ### Change pg_cron Extension Settings Source: https://github.com/citusdata/pg_cron/blob/main/README.md Modify a pg_cron extension parameter using the `ALTER SYSTEM` command. Note that some settings require a server restart or configuration reload to take effect. ```sql ALTER SYSTEM SET cron. TO ''; ``` -------------------------------- ### Remove a Scheduled Job with cron.unschedule Source: https://context7.com/citusdata/pg_cron/llms.txt Removes a job by its integer `jobid` or its text name. Returns `true` if the job was found and removed, `false` otherwise. Users can only unschedule their own jobs. ```sql SELECT cron.unschedule('nightly-vacuum'); ``` ```sql SELECT cron.unschedule(42); ``` ```sql DO $$ BEGIN IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'old-job') THEN PERFORM cron.unschedule('old-job'); RAISE NOTICE 'Job removed'; ELSE RAISE NOTICE 'Job not found, nothing to remove'; END IF; END; $$; ``` -------------------------------- ### Alter a Cron Job Source: https://github.com/citusdata/pg_cron/blob/main/README.md Allows modification of existing cron job parameters such as schedule, command, database, username, and active status. Takes the job ID as the primary identifier. ```APIDOC ## cron.alter_job ### Description Modifies an existing cron job. Any parameters not specified will retain their current values. ### Signature ```sql CREATE OR REPLACE FUNCTION cron.alter_job( job_id bigint, schedule text DEFAULT NULL::text, command text DEFAULT NULL::text, database text DEFAULT NULL::text, username text DEFAULT NULL::text, active boolean DEFAULT NULL::boolean ) RETURNS void ``` ### Parameters - **job_id** (bigint) - Required - The ID of the job to alter. - **schedule** (text) - Optional - The new cron schedule string. - **command** (text) - Optional - The new SQL command to execute. - **database** (text) - Optional - The new database in which to run the command. - **username** (text) - Optional - The new database user to run the command as. - **active** (boolean) - Optional - The new active status for the job. ### Examples ##### Change a job's schedule ```sql -- change job's schedule SELECT cron.alter_job(42, '0 10 * * *'); -- returns void ``` ##### Change a job's, schedule, command, and username ```sql -- change job's command SELECT cron.alter_job( 42, '0 10 * * *', 'VACUUM', username := 'some_other_user' ); -- returns void ``` ##### Deactivate a job ```sql -- deactivate job SELECT cron.alter_job(42, active := false); -- returns void ``` ``` -------------------------------- ### cron.alter_job Source: https://context7.com/citusdata/pg_cron/llms.txt Modifies properties of an existing job. Only non-NULL arguments are applied, allowing for selective updates to schedule, command, database, username, or active status without dropping and re-creating the job. ```APIDOC ## `cron.alter_job` — Modify an Existing Job Updates one or more properties of an existing job identified by its `jobid`. All parameters except `job_id` are optional — only non-NULL arguments are applied. This is the recommended way to enable/disable jobs or update schedules without dropping and re-creating them. ### Signature ```sql -- Signature cron.alter_job( job_id bigint, schedule text DEFAULT NULL, command text DEFAULT NULL, database text DEFAULT NULL, username text DEFAULT NULL, active boolean DEFAULT NULL ) RETURNS void ``` ### Examples Change only the schedule of job 7: ```sql SELECT cron.alter_job(7, '0 3 * * *'); ``` Change schedule and command together: ```sql SELECT cron.alter_job( 7, '0 3 * * 1-5', 'VACUUM ANALYZE orders, customers' ); ``` Change only the executing username (named parameter style): ```sql SELECT cron.alter_job(7, username := 'maintenance_user'); ``` Disable a job without deleting it (can be re-enabled later): ```sql SELECT cron.alter_job(7, active := false); ``` Re-enable a previously disabled job: ```sql SELECT cron.alter_job(7, active := true); ``` Move a job to run in a different database: ```sql SELECT cron.alter_job(7, database := 'new_app_db'); ``` Full update: reschedule, new command, new user, re-enable: ```sql SELECT cron.alter_job( 7, '30 1 * * *', 'CALL full_maintenance()', 'app_db', 'admin', true ); ``` ``` -------------------------------- ### Remove a Cron Job Source: https://github.com/citusdata/pg_cron/blob/main/README.md Provides two overloaded functions to remove cron jobs, either by their name or by their unique ID. Returns true if the job was successfully removed. ```APIDOC ## cron.unschedule ### Description Removes a cron job from the scheduler. Can be called with either the job's name or its ID. ### Signatures 1. **Remove by name:** ```sql CREATE OR REPLACE FUNCTION cron.unschedule(job_name text) RETURNS boolean ``` 2. **Remove by ID:** ```sql CREATE OR REPLACE FUNCTION cron.unschedule(job_id bigint) RETURNS boolean ``` ### Parameters - **job_name** (text) - Required (for the first signature) - The name of the job to remove. - **job_id** (bigint) - Required (for the second signature) - The ID of the job to remove. ### Examples ##### Remove a named cron job ```sql -- delete job by name SELECT cron.unschedule('nightly-vacuum'); -- returns true if job was removed ``` ##### Remove a cron job by id ```sql -- delete job by id SELECT cron.unschedule(42); -- returns true if job was removed ``` ``` -------------------------------- ### Alter a Cron Job's Schedule Source: https://github.com/citusdata/pg_cron/blob/main/README.md Modify the schedule of an existing cron job using `cron.alter_job` by providing the job ID and the new schedule. The function returns `void` upon completion. ```sql CREATE OR REPLACE FUNCTION cron.alter_job( job_id bigint, schedule text DEFAULT NULL::text, command text DEFAULT NULL::text, database text DEFAULT NULL::text, username text DEFAULT NULL::text, active boolean DEFAULT NULL::boolean ) RETURNS void ``` ```sql -- change job's schedule SELECT cron.alter_job(42, '0 10 * * *'); -- returns void ``` -------------------------------- ### cron.unschedule Source: https://context7.com/citusdata/pg_cron/llms.txt Removes a scheduled job from the `cron.job` table. Jobs can be removed by their integer `jobid` or their text name. The function returns `true` if the job was found and removed, and `false` otherwise. Users can only unschedule jobs they own. ```APIDOC ## `cron.unschedule` — Remove a Scheduled Job Removes a job from `cron.job` either by its integer `jobid` or by its text name. Returns `true` if the job was found and removed, `false` otherwise. Users can only unschedule their own jobs. ### Signature (by name) `cron.unschedule(job_name text) RETURNS boolean` ### Signature (by id) `cron.unschedule(job_id bigint) RETURNS boolean` ### Examples Remove a named job: ```sql SELECT cron.unschedule('nightly-vacuum'); -- returns: t ``` Remove a job by its numeric id: ```sql SELECT cron.unschedule(42); -- returns: t ``` Defensive removal: only unschedule if it exists: ```sql DO $$ BEGIN IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'old-job') THEN PERFORM cron.unschedule('old-job'); RAISE NOTICE 'Job removed'; ELSE RAISE NOTICE 'Job not found, nothing to remove'; END IF; END; $$; ``` ``` -------------------------------- ### Remove a Cron Job by Name Source: https://github.com/citusdata/pg_cron/blob/main/README.md Use `cron.unschedule` with the job name to remove a specific cron job. This function returns `true` if the job was successfully removed, and `false` otherwise. ```sql -- remove job by name, return true if job was removed CREATE OR REPLACE FUNCTION cron.unschedule(job_name text) RETURNS boolean ``` ```sql -- delete job by name SELECT cron.unschedule('nightly-vacuum'); -- returns true if job was removed ``` -------------------------------- ### Deactivate a Cron Job Source: https://github.com/citusdata/pg_cron/blob/main/README.md Disable a cron job by setting its `active` status to `false` using the `cron.alter_job` function. This is useful for temporarily stopping a job without removing it. ```sql -- deactivate job SELECT cron.alter_job(42, active := false); -- returns void ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.