pg_cron 插件实现定时任务

pg_cron

  • 安装
  • 使用

安装

git clone https://github.com/citusdata/pg_cron.git
cd pg_cron
export PATH=/usr/local/pgsql/bin:$PATH
make && make install

使用

  • 修改配置文件
vim postgresql.auto.conf
[postgres@node01 data]$ tail -2 postgresql.auto.conf 
shared_preload_libraries = 'pg_cron'
cron.database_name = 'test'  # 根据实际情况, 修改指定为你想要创建定时任务的的数据库

# 可选
cron.use_background_workers = on
max_worker_processes = 20
  • 设置 本地免密登录
vim pg_hba.conf
local   all             all                                     trust  # 主要是第一行配置是必须的
...

  • 创建扩展
psql -U postgres -d test
create extension pg_cron;
SELECT * FROM cron.job;

test=# create extension pg_cron;
CREATE EXTENSION
test=# SELECT * FROM cron.job;  
 jobid | schedule | command | nodename | nodeport | database | username | active | jobname 
-------+----------+---------+----------+----------+----------+----------+--------+---------
(0 rows)

  • 测试
create table test(id int);
SELECT cron.schedule('* * * * *','insert into test values(1);');  -- 配置定时任务
select * from cron.job;     -- 查看当前定时任务配置
select * from cron.job_run_details ;                 -- 查看运行过的定时任务

 jobid | runid | job_pid | database | username |           command           |  status   | return
_message |          start_time           |           end_time            
-------+-------+---------+----------+----------+-----------------------------+-----------+-------
---------+-------------------------------+-------------------------------
     1 |     1 |     907 | test     | postgres | insert into test values(1); | succeeded | INSERT
 0 1     | 2023-04-15 19:30:00.008648+08 | 2023-04-15 19:30:00.011271+08
(1 rows)

test=# select * from test;
 id 
----
  1
(1 rows)


CREATE OR REPLACE FUNCTION func_test(int)
RETURNS int
AS $BODY$ 
DECLARE
BEGIN
    insert into test values($1);
    return 0;
END; 
$BODY$  LANGUAGE plpgsql ;

SELECT cron.schedule('* * * * *','select func_test(10);');
select * from test;
test=# select * from test;
 id 
----
  1
  1
  1
  1
  1
  1
  1
  1
  1
  1
  1
 10
  1

你可能感兴趣的:(数据库)