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:
Does postgresql have any native (inbuilt) functionality that I can build upon to achieve this behaviour?
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.
PostgreSQL doesn't have the concept of scheduled jobs.
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.
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 .
pgAgent will do the job. A complete setup can be found at Postgresonline.com.
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'"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With