问题
I need to create a cron that runs every night and remove some of the data (older ones) from my database. I am running postgres on debian. How do I do that? My server is tomcat6. Does anyone have a step by step instruction including script to do that?
回答1:
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
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/11250590/cron-job-to-remove-old-data-from-postgres-on-debian