tmsblgh
tmsblgh

Reputation: 527

Timed method in Python

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.

Upvotes: 2

Views: 115

Answers (3)

gonczor
gonczor

Reputation: 4136

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.

Upvotes: 0

Stanislav Ivanov
Stanislav Ivanov

Reputation: 1974

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

Upvotes: 1

turkus
turkus

Reputation: 4893

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.

Upvotes: 0

Related Questions