pg_cron icon indicating copy to clipboard operation
pg_cron copied to clipboard

Add a next_runtime function

Open melquelima opened this issue 1 year ago • 5 comments

would be great to have a column called next_runtime or a way to calculate next run time like

select cron.next_runtime('* * * * *')

melquelima avatar Jul 31 '24 19:07 melquelima

+1

xx789633 avatar Nov 05 '24 13:11 xx789633

@cwang9208 ive created a code that does that for me check this out

next run time

import pycron
from datetime import datetime,timedelta
import pytz

def next_runtime(s:str)
  dt = datetime.now()
  
  while True:
      if pycron.is_now(s, dt):
          return dt.replace(second=0, microsecond=0)
      dt += timedelta(minutes=1)

last run time

import pycron
from datetime import datetime,timedelta
import pytz

def last_runtime(s:str)
  dt = datetime.now()
  
  while True:
      if pycron.is_now(s, dt):
          return dt.replace(second=0, microsecond=0)
      dt -= timedelta(minutes=1)
    

POSTGRES


// ================================ PYTHON + PYCRON
CREATE EXTENSION IF NOT EXISTS plpython3u

CREATE EXTENSION IF NOT EXISTS pg_cron;


CREATE or replace function  get_last_runtime (s varchar)
  RETURNS VARCHAR
AS $$
 
import pycron
from datetime import datetime,timedelta
import pytz

dt = datetime.now()

while True:
    if pycron.is_now(s, dt):
        return dt.replace(second=0, microsecond=0)
    dt -= timedelta(minutes=1)


$$ LANGUAGE plpython3u;


CREATE or replace function  get_next_runtime (s varchar)
  RETURNS VARCHAR
AS $$
 
import pycron
from datetime import datetime,timedelta
import pytz

dt = datetime.now()

while True:
    if pycron.is_now(s, dt):
        return dt.replace(second=0, microsecond=0)
    dt += timedelta(minutes=1)


$$ LANGUAGE plpython3u;

melquelima avatar Nov 05 '24 15:11 melquelima

@melquelima https://github.com/cybertec-postgresql/pg_timetable/blob/master/internal/pgengine/sql/cron.sql this might be useful.

xx789633 avatar Nov 07 '24 03:11 xx789633

@marcoslot @marcocitus Is it possible to calculate the next run date using the entry data structure in pg_cron's source code? Could you please help.

xx789633 avatar Nov 07 '24 04:11 xx789633

Any word on if this will be accepted? It would be hugely valuable for me!

cvburgess avatar Apr 29 '25 16:04 cvburgess