How to execute a function asynchronously every 60 seconds in Python?

aF. picture aF. · Feb 8, 2010 · Viewed 77.2k times · Source

I want to execute a function every 60 seconds on Python but I don't want to be blocked meanwhile.

How can I do it asynchronously?

import threading
import time

def f():
    print("hello world")
    threading.Timer(3, f).start()

if __name__ == '__main__':
    f()    
    time.sleep(20)

With this code, the function f is executed every 3 seconds within the 20 seconds time.time. At the end it gives an error and I think that it is because the threading.timer has not been canceled.

How can I cancel it?

Thanks in advance!

Answer

David Underhill picture David Underhill · Feb 8, 2010

You could try the threading.Timer class: http://docs.python.org/library/threading.html#timer-objects.

import threading

def f(f_stop):
    # do something here ...
    if not f_stop.is_set():
        # call f() again in 60 seconds
        threading.Timer(60, f, [f_stop]).start()

f_stop = threading.Event()
# start calling f now and every 60 sec thereafter
f(f_stop)

# stop the thread when needed
#f_stop.set()