Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run queries periodically (ala crontab) from a postgresql database

Tags:

sql

postgresql

I am trying to replicate (a mininimal) crontab functionality in a postgresql database table with crontab-like semantics as follows below (indices not shown, for simiplicity):

create table schedule (
id int not null primary key,
command text
);

create table schedule_detail(
schedule_id int not null references schedule(id),
sd_minute smallint not null,
sd_hour smallint not null,
sd_day smallint not null,
sd_month smallint not null,
sd_year smallint not null,
sd_dayofweek smallint not null
);

I have only got as far as the schema design. I would like some ideas on how I can implement this. In particular, how to implement:

  1. The 'periodic polling' of the schedule table
  2. How to determine which schedule to be run

Does postgresql have any native (inbuilt) functionality that I can build upon to achieve this behaviour?

like image 900
skyeagle Avatar asked Dec 13 '10 23:12

skyeagle


People also ask

Does PostgreSQL have a scheduler?

Scheduling allows you to automate things so you don't have to do them in real time. In this article we will see how to schedule a job in PostgreSQL. We'll use pgAgent, a job scheduling agent for PostgreSQL.

How do I create a scheduled job in PostgreSQL?

PostgreSQL doesn't have the concept of scheduled jobs.

What is PostgreSQL crontab?

The pg_cron is a cron-based job scheduler for PostgreSQL that runs inside the database as an extension (similar to the DBMS_SCHEDULER in Oracle) and allows the execution of database tasks directly from the database, due to a background worker. The tasks to perform can be any of the following ones: stored procedures.

How do I run a query in PostgreSQL?

To do this in PL/pgSQL, use the PERFORM statement: PERFORM query ; This executes query and discards the result. Write the query the same way you would write an SQL SELECT command, but replace the initial keyword SELECT with PERFORM .


2 Answers

pgAgent will do the job. A complete setup can be found at Postgresonline.com.

like image 194
Frank Heikens Avatar answered Sep 19 '22 12:09

Frank Heikens


I have been using psql + crontab for it. Like this :

This crontab entry will delete content older than 60 days on rolling basis.

0 16 * * * PGPASSWORD=mypassword psql -Umyuser -dmyschema -c "delete from mytable where created_at < now() - interval '60 days'"
like image 29
mdev Avatar answered Sep 20 '22 12:09

mdev