2

How do I have a part of python script(only a method, the whole script runs in 24/7) run everyday at a set-time, exactly at every 20th minutes? Like 12:20, 12:40, 13:00 in every hour.

I can not use cron, I tried periodic execution but that is not as accurate as I would... It depends from the script starting time.

tmsblgh
  • 517
  • 5
  • 21
  • 2
    Why can't you use cron? Periodic execution in your script could also work if you `time.sleep(time_to_wake_up - the_current_time)` in the periodic process. – larsks Sep 01 '16 at 13:31
  • If you want accuracy, you won't beat cron. – Łukasz Rogalski Sep 01 '16 at 13:33
  • Short ? `if divmod(int(time.strftime('%M')),20)[1] == 0:#do_somethings`. But need a flag `on_related_minute` for non-duplicate ! – dsgdfg Sep 01 '16 at 14:28

3 Answers3

1

Module schedule may be useful for this. See answer to How do I get a Cron like scheduler in Python? for details.

Community
  • 1
  • 1
Stanislav Ivanov
  • 1,854
  • 1
  • 16
  • 22
0

You can either put calling this method in a loop, which would sleep for some time

from time import sleep
while True:
    sleep(1200)
    my_function()

and be triggered once in a while, you could use datetime to compare current timestamp and set next executions.

import datetime

function_executed = False
trigger_time = datetime.datetime.now()

def set_trigger_time():
    global function executed = False
    return datetime.datetime.now() + datetime.timedelta(minutes=20)

while True:
    if function_executed:
        triggertime = set_trigger_time()

    if datetime.datetime.now() == triggertime:
        function_executed = True
        my_function()

I think however making a system call the script would be a nicer solution.

crookedleaf
  • 2,118
  • 4
  • 16
  • 38
gonczor
  • 3,994
  • 1
  • 21
  • 46
  • The 2nd method won't work (trigger time is reset in every iteration, always 20 minutes ahead, the condition will always be `False`). Even if the logic was correct, it would busy-wait the CPU to death, since it never sleeps – salezica Sep 01 '16 at 13:52
  • Oh, yes, indeed. It would need some kind of flag marking execution. And it definately will be CPU consuming. – gonczor Sep 01 '16 at 13:54
0

Use for example redis for that and rq-scheduler package. You can schedule tasks with specific time. So you can run first script, save to the variable starting time, calculate starting time + 20 mins and if your current script will end, at the end you will push another, the same task with proper time.

turkus
  • 4,637
  • 2
  • 24
  • 28