postgresql定时任务-pg_cron

pg_cron是Citus Data研发的一个PostgreSQL扩展。它包含一个后台工作程序 (pg_cron scheduler),用于在服务器端执行数据库任务。它使用与常规cron相同的语法,允许直接从数据库定期执行PostgreSQL命令。

源码编译

源码下载:https://github.com/citusdata/pg_cron


#Ensure pg_config is in your path
    export PATH=/home/postgres/pgsql/bin:$PATH
#编译
make && make install

postgresql.conf配置


postgresql.conf配置文件修改
#required to load pg_cron background worker on start-up
shared_preload_libraries = 'pg_cron'
#optionally, specify the database in which the pg_cron background worker should run (defaults to postgres)
cron.database_name = 'postgres'
#optionally, specify the timezone in which the pg_cron background worker should run (defaults to GMT). E.g: PRC东八区
cron.timezone = 'PRC'
#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
#pg_cron config
cron.timezone = 'PRC'
cron.use_background_workers = on
cron.database_name = 'cptest'

创建extension


-- run as superuser:
CREATE EXTENSION pg_cron;
-- optionally, grant usage to regular users:
GRANT USAGE ON SCHEMA cron TO cpuser;

测试

上线定时任务

#定时任务创建分区表

postgresql定时任务-pg_cron_第1张图片

-- 1. ensure we have partitions for the next 12 months
SELECT cron.schedule('create-partitions', '0 0 1 * *', $$
SELECT create_time_partitions(
table_name         := 'user_info',
partition_interval := '1 hour',
end_at             := now() + '1 months'
)
$$);
#清理24小时之前的分区表
-- 2. (optional) ensure we never have more than one year of data
SELECT cron.schedule('drop-partitions', '50 * * * ', $$CALL drop_old_time_partitions('user_info',now() - interval '24 hours' / older_than */
);
$$);

下线定时任务


select cron.unschedule('drop-partitions' );unschedule
t
(1 row)
postgresql定时任务-pg_cron_第2张图片

查询定时任务

select * from cron.job;

你可能感兴趣的:(PostgreSQL,Citus,postgresql,数据库)