I have a bot that has to run continuously but I want it to call one particular functionality only during working time of business day. Someone suggested me to do that with crontab but If I am not mistaken, this is not possible for two reasons:
I need to run my bot as a docker image (so in ALpine-Lynux) and crontab does not support lynux os
it just allows me to repeat an action every given seconds/minutes/hours/days and there is no possible way to "say it" ("if I am in a working time of a business day run the action continuously otherwise just wait 9am of next working day")
This is what I am building, I would like to know which of the 2 "versions" of the wait function is better but if you know any smartest way, it will be appreciated a lot
def waiting_or_not():
current_date = datetime.now(timezone('Europe/Rome'))
need_to_wait = True
if not isbday(current_date, holidays=Italy()) or current_date.hour > 18:
next_run = get_next_working_day(current_date.replace(hour=9, minute=0, second=0) + timedelta(days=1))
elif current_date.hour < 9:
next_run = current_date.replace(hour=9, minute=0, second=0)
else:
need_to_wait = False
if need_to_wait:
seconds_to_wait = (next_run - current_date).total_seconds()
# insert log
wait(next_run)
def get_next_working_day(date_):
while not isbday(date_):
date_ += timedelta(days=1)
return date_
def wait(next_run):
'''
I don't like this version at all. It seems to me ridiculous to "ask" continuously
the time. If it is friday evening after 18 and I need to wait until Monday morning,
there will be billions of useless checks.
'''
current_date = datetime.now(timezone('Europe/Rome'))
while current_date < next_run:
current_date = datetime.now(timezone('Europe/Rome'))
def wait(next_run):
'''
I read sleep function is not precise and has big problems with huge numbers of seconds
'''
current_date = datetime.now(timezone('Europe/Rome'))
time.sleep((next_run - current_date).total_seconds())