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.

3
  • 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. Commented Sep 1, 2016 at 13:31
  • If you want accuracy, you won't beat cron. Commented Sep 1, 2016 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 ! Commented Sep 1, 2016 at 14:28

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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
Oh, yes, indeed. It would need some kind of flag marking execution. And it definately will be CPU consuming.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.