Use pg_cron to Schedule Jobs
Run recurring SQL statements inside your Managed PostgreSQL service with pg_cron, a scheduler that stores its jobs in the database.
Before You Start
Open a
psqlsession asavnadminon thedefaultdbdatabase. See Connect with psql.Check the version offered on your service:
SELECT name, default_version FROM pg_available_extensions WHERE name = 'pg_cron';
Enable the Extension
In defaultdb:
CREATE EXTENSION pg_cron;The extension is registered in pg_catalog and creates a cron schema with the cron.job and
cron.job_run_details tables and the scheduling functions.
Important
defaultdb is the only database that accepts the extension. Elsewhere,
CREATE EXTENSION pg_cron fails with
ERROR: can only create extension in database defaultdb. Schedule every job from
defaultdb, and use cron.schedule_in_database() for statements that must run in another
database. The cron.* settings, such as cron.database_name and cron.timezone, cannot be
read by avnadmin: SHOW fails with permission denied to examine.
Schedule a Job
cron.schedule() takes a job name, a schedule and the SQL statement, and returns the job ID:
SELECT cron.schedule(
'nightly-vacuum',
'0 2 * * *',
'VACUUM ANALYZE public.orders'
);Use dollar quoting when the statement contains single quotes:
SELECT cron.schedule(
'purge-sessions',
'15 3 * * *',
$$DELETE FROM public.sessions WHERE expires_at < now()$$
);Scheduling again under an existing name replaces that job, keeping its ID. This is how you change the schedule or the statement of a named job.
The schedule is a five-field cron expression (minute, hour, day of month, month, day of week, with Sunday as 0), or an interval of 1 to 59 seconds:
| Schedule | Runs |
|---|---|
* * * * * | Every minute |
*/5 * * * * | Every five minutes |
0 2 * * * | Every day at 02:00 |
15 3 * * 0 | Every Sunday at 03:15 |
0 0 1 * * | At midnight on the first day of every month |
30 seconds | Every 30 seconds |
Tip
Check the start_time of the first runs in cron.job_run_details to confirm when a job fires.
Times are stored as timestamptz.
Run a Job in Another Database
The job is stored in defaultdb, but the statement can run in another database of the service:
SELECT cron.schedule_in_database(
'purge-sessions-app',
'15 3 * * *',
$$DELETE FROM public.sessions WHERE expires_at < now()$$,
'DATABASE_NAME'
);Parameters:
DATABASE_NAME: database in which the statement runs. It must exist on the service.
The job runs as the user that created it. The optional fifth argument of
cron.schedule_in_database(), a user name, cannot be set to another role:
avnadmin gets ERROR: must be superuser to create a job for another role. To run a job as
another role, let that role schedule it, see Let Another User Schedule Jobs.
List the Jobs
SELECT jobid, jobname, schedule, database, username, active, command
FROM cron.job
ORDER BY jobid;avnadmin sees the jobs of every user. Other users see only their own.
Read the Job History
Every run is recorded in cron.job_run_details:
SELECT jobid, runid, database, status, return_message, start_time, end_time
FROM cron.job_run_details
ORDER BY start_time DESC
LIMIT 10;A failed run has status = 'failed' and the PostgreSQL error in return_message, for example
ERROR: schema "partman" does not exist for a statement scheduled in the wrong database.
The table is not trimmed automatically. Schedule a cleanup:
SELECT cron.schedule(
'prune-cron-history',
'0 4 * * *',
$$DELETE FROM cron.job_run_details WHERE end_time < now() - interval '7 days'$$
);Change, Disable or Remove a Job
Disable a job without deleting it:
SELECT cron.alter_job(job_id := JOB_ID, active := false);cron.alter_job() also accepts schedule, command and database. Arguments you leave out keep
their value.
Remove a job by name or by ID:
SELECT cron.unschedule('nightly-vacuum');SELECT cron.unschedule(JOB_ID);Parameters:
JOB_ID: thejobidfromcron.job.
Let Another User Schedule Jobs
Allow a service user to use the scheduler:
GRANT USAGE ON SCHEMA cron TO USERNAME;Parameters:
USERNAME: an existing service user, created for example withexo dbaas user create SERVICE_NAME USERNAME -z ZONE.
That user connects to defaultdb and calls cron.schedule() itself. Its jobs run as that user,
which needs the privileges the statement requires.
avnadmin can list these jobs but cannot remove them: cron.unschedule() on another user’s job
fails with permission denied for table job. Remove them as their owner.
Overlapping Runs
Different jobs can run at the same time. A job never runs twice in parallel: if a run is still going when the next one is due, the next run starts as soon as the current one finishes. Keep the schedule of a long job wider than its usual duration.
Jobs run on the primary only. A
read replica has the same
cron.job rows as its source. When you promote a replica, review cron.job on it and disable
jobs that must not run on two services.