Skip to content
Advertisement

Python does something every 5 minutes

i need to check data on an API. The API is refreshed with new data every 5 minutes (10:00, 10:05, 10:10 etc…)

I don’t want to use time.sleep(300) because i want my script to do something at 10:05:03, then 10:05:03 etc. and not 5 min avec the script started (maybe it started at 10h12 How can i build this?

Thanks y’all.

Advertisement

Answer

UPDATE:

Just wanted to remove the possibility of recursion error, so I have rewritten the code:

from threading import Thread
from time import sleep
import datetime

def check_api():
    # ... your code here ...
    pass

def schedule_api():
    while datetime.datetime.now().minute % 5 != 0:
        sleep(1)
    check_api()
    while True:
        sleep(300)
        check_api()

thread = Thread(target=schedule_api)
thread.start()

Also if you want your thread to quit when the main program exits you could set daemon as True on the thread like:

thread.daemon = True

But this does not enforce a clean termination of this thread so you could also try this approach below:

# ...
RUNNING = True
# ...
thread = Thread(target=schedule_api)
thread.start()
#...
def main():
    # ... all main code ...
    pass

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        RUNNING = False


You can use the following code:

import threading

def check_api():
    pass

timer_thread = threading.Timer(300, check_api)
timer_thread.start()
# call timer_thread.cancel() when you need it to stop

This will call your check_api function every 5 minutes and will not block your main code’s execution.

as mentioned by @scotyy3785 the above code will only run once but I realize what you want and have written the code for it:

from threading import Thread
from time import sleep
import datetime


def check_api():
    # ... your code here ...
    pass


def caller(callback_func, first=True):
    if first:
        while not datetime.datetime.now().minute % 5 == 0:
            sleep(1)
    callback_func()
    sleep(300)
    caller(callback_func, False)


thread = Thread(target=caller, args=(check_api,))
thread.start()

# you'll have to handle the still running thread on exit

The above code will call check_api at minutes like 00, 05, 10, 15…

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement