Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a cron job to run an postgres SQL function?

I assume that all I need to do is to:

  1. Create an sql file e.g. nameofsqlfile.sql contents:

    perform proc_my_sql_funtion();

  2. Execute this as a cron job.

However, I don't know the commands that I'd need to write to get this cron job executed as a postgres function for a specified host,port,database, user & his password...?

like image 648
Phil Avatar asked Oct 18 '11 09:10

Phil


People also ask

How do I create a scheduled job in PostgreSQL?

In the Schedules tab we add the start date time and the end date time for the job to start and end. SQL is the last tab. It shows the code generated by the GUI. If you want to schedule a job dynamically you will have to execute the procedure code displayed here.

What is cron job in PostgreSQL?

pg_cron is a simple cron-based job scheduler for PostgreSQL (10 or higher) that runs inside the database as an extension. It uses the same syntax as regular cron, but it allows you to schedule PostgreSQL commands directly from the database: -- Delete old data on Saturday at 3:30am (GMT) SELECT cron.

Does PostgreSQL have a scheduler?

Starting with PostgreSQL version 12.5 and higher, Amazon RDS for PostgreSQL now supports the extension pg_cron, a simple cron-based job scheduler for PostgreSQL that runs inside the database.

What is * * * * * In cron job?

What does * mean in Cron? The asterisk * is used as a wildcard in Cron. * sets the execution of a task to any minute, hour, day, weekday, or month.


2 Answers

You just need to think of cronjob as running a shell command at a specified time or day.

So your first job is to work out how to run your shell command.

psql --host host.example.com --port 12345 --dbname nameofdatabase --username postgres < my.sql

You can then just add this to your crontab (I recommend you use crontab -e to avoid breaking things)

# runs your command at 00:00 every day
#
# min hour wday month mday command-to-run
    0    0    *     *    * psql --host host.example.com --port 12345 --dbname nameofdatabase < my.sql
like image 159
Matthew Rudy Avatar answered Oct 01 '22 17:10

Matthew Rudy


In most cases you can put all of the sql source in a shell 'here document'. The nice thing about here documents is that the shell's ${MY_VAR} are expanded even within single quotes, e.g:

#!/bin/sh

THE_DATABASE=personnel
MY_TABLE=employee
THE_DATE_VARIABLE_NAME=hire_date
THE_MONTH=10
THE_DAY=01

psql ${THE_DATABASE} <<THE_END
  SELECT COUNT(*) FROM ${MY_TABLE}
  WHERE ${THE_DATE_VARIABLE_NAME} >= '2011-${THE_MONTH}-${THE_DAY}'::DATE
THE_END

YMMV

like image 43
wildplasser Avatar answered Oct 01 '22 15:10

wildplasser