cron job to remove old data from postgres on debian

夙愿已清 提交于 2019-12-02 05:00:29

in most cases, I prefer a shell script with an here-document. (shell-variables expand nicely in here-documents):

#!/bin/sh
PSQL=/local/postgres/bin/psql
SOME_VALUE=123

$PSQL my_database <<THE_END
DELETE FROM my_table
WHERE my_column <= $SOME_VALUE
    ;
THE_END

Several good ways.
You may want to do more than just one DELETE. Run ANALYZE tbl? Handle multiple tables?
I would wrap the work in a a plpgsql function:

CREATE OR REPLACE FUNCTION myschema.f_maintain()
  RETURNS text AS
$BODY$
DECLARE
    _msg    text := 'Report';
    _min_ts timestamp := now()::timestamp - interval '5y'; -- max. age 5 years
    _count  int;
BEGIN

DELETE FROM tbl
WHERE  my_ts < _min_ts
AND    <some condition>;

GET DIAGNOSTICS _count = ROW_COUNT;

IF _count > 0 THEN
    _msg := _msg || E'\nDeleted rows in tbl: ' || _count;
END IF;

ANALYZE tbl;

-- more ?

RAISE LOG '%', _msg;

END;
$BODY$
  LANGUAGE plpgsql;

... and call it from the shell like this:

psql -p 5432 event -c 'SELECT myschema.f_maintain()'

Schedule a cron job for the system user postgres:

crontab -e

To run it every day at 02:06, add a line like:

06 02 * * * psql -p 5432 event -c 'SELECT myschema.f_maintain()' >/dev/null

You can put a direct call to psql right in /etc/crontab. The call would follow this pattern:

psql -c 'DELETE FROM my_table WHERE ...'

You would need to supply the appropriate additional arguments to 'psql' to create the database connection. See the documentation for psql for more information about that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!