Postgresql配置定时任务——pg_cron

1、说明

pg_cron是postgresql的一个扩展,是一个基于cron的作业调度程序,需要pg9.5及以上版本才可以安装。
它的用法和操作系统的cron基本一致,但是允许我们直接在postgresql数据库中执行sql语句。并且作为一个独立运行的工作者进程,其生命周期管理、内存空间都依赖于 postgreSQL 。
例如我们安装完该插件后,可以看到相关的进程:
在这里插入图片描述

2、安装

下载地址:
https://github.com/citusdata/pg_cron

编译安装:

cd pg_cron
make
make install

配置参数:
因为pg_cron会启动一个新的进程,所以需要将其添加到shared_preload_libraries参数中。
同时我们还需要配置cron.database_name指定数据库。

shared_preload_libraries = 'pg_cron' 
cron.database_name = 'bill'

另外我们还需要配置pg_hba.conf:

host    all    all   localhost        trust
host    all   all  0.0.0.0/0     trust

或者配置.pgpass文件也可以:

hostname:port:database:user:password

然后重启数据库就可以安装该扩展了:

pg_ctl stop
pg_ctl start
CREATE EXTENSION pg_cron;

3、使用

我们先看下该扩展为我们提供了哪些函数:

bill=# \dx+ pg_cron 
    Objects in extension "pg_cron"
          Object description          
--------------------------------------
 function cron.job_cache_invalidate()
 function cron.schedule(text,text)
 function cron.unschedule(bigint)
 schema cron
 sequence cron.jobid_seq
 table cron.job
(6 rows)
  • cron.schedule:创建定时任务,其中第一个参数是执行频率,第二个参数是执行的任务。
  • cron.unschedule:取消定时任务,参数为jobid。

创建定时任务:

bill=# SELECT cron.schedule('0 10 * * *', 'VACUUM');
 schedule 
----------
        1
(1 row)

查看定时任务:

bill=# select * from cron.job;
 jobid |  schedule  | command | nodename  | nodeport | database | username | active 
-------+------------+---------+-----------+----------+----------+----------+--------
     1 | 0 10 * * * | VACUUM  | localhost |     1921 | bill     | bill     | t
(1 row)

取消定时任务:

bill=# SELECT cron.unschedule(1); 
 unschedule 
------------
 t
(1 row)

或者我们可以直接删除cron.job表中对应的记录也可以取消定时任务。

pg_cron 使用标准的 cron 语法,其中 * 表示“每个该时间运行”,特定数字表示“仅在 这个数字时 运行”

┌───────────── 分钟 (0 - 59)
 │ ┌────────────── 小时 (0 - 23)
 │ │ ┌─────────────── 日期 (1 - 31)
 │ │ │ ┌──────────────── 月份 (1 - 12)
 │ │ │ │ ┌───────────────── 一周中的某一天 (0 - 6) (06 表示周末到下周六,
 │ │ │ │ │                   7 仍然是周末)
 │ │ │ │ │
 │ │ │ │ │
* * * * *

猜你喜欢

转载自blog.csdn.net/weixin_39540651/article/details/108389215