pg_cron is a cron-based PostgreSQL task scheduler extension. Its syntax is the same as cron and can execute PostgreSQL commands directly from the database.
Time-based scheduling adopts the standard cron syntax, where * means running at any time, and specific numbers mean running only at those times.
Extension usage
Create extension
- Modify parameter shared_preload_libraries to add the value pg_cron. For detailed information on modifying parameters, please refer to Modifying parameters.
- Use a super account to create the extension by executing the following command in the postgres database.
Delete extension
Execute the following command to delete the extension.
Extension usage
Creating a scheduled task
pg_cron provides two functions, cron.schedule() and cron.schedule_in_database(), to create scheduled tasks.
- The usage syntax of the cron.schedule() function is as follows:
-
- cron.schedule_in_database() function
- The usage syntax of the cron.schedule_in_database() function is as follows:
-
tip
- The cron.schedule_in_database() function cannot specify the User. In cron.schedule_in_database ('<Name>', '<Schedule>', '<Task>', '<Database>', '<User>', '<Is enabled>'), the '<User>' can only be filled with NULL.
- RDS for PostgreSQL does not open "super user" accounts to users. Do not try to use a PostgreSQL "super user" account to use this extension, otherwise an error is reported.
View scheduled tasks
You can view configured scheduled tasks in the cron.job table.
And view the task status and execution status in the cron.job_run_details table.
Modify scheduled tasks
The syntax for modifying a scheduled task is as follows:
Examples:
tip
cron.alter_job() function cannot specify a user. cron.alter_job ('<Task ID>', '<schedule>', '<task>', '<Database>', '<User>', '<enabled>') requires '<User>' to be filled with NULL only.
Cancel a scheduled task
The syntax for canceling a scheduled task is as follows:
Examples:
Authorizing a general user to use the extension
The syntax for authorizing a general user to use the extension is as follows:
Examples:
tip
Ordinary users cannot execute cron.schedule_in_database() and cron.alter_job() functions.
Related parameters
You need to use the following two parameters while using the pg_cron extension:
- shared_preload_libraries: before creating the pg_cron extension, modify this parameter to add the pg_cron value.
- cron.log_run: enables or disables logging all running tasks to the cron.job_run_details table, which is enabled by default. This parameter accepts on and off values, with the default value of on.
tip
- After modifying shared_preload_libraries and cron.log_run parameters, restart the instance to apply the changes.