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!
I googled around and found the Python circuits Framework, which makes it possible to wait
for a particular event.
The
.callEvent(self, event, *channels)
method of circuits contains a fire and suspend-until-response functionality, the documentation says:I hope you find it as useful as I do :)
./regards
Why dont you create a dedicated thread, in which you put a simple sleeping loop:
If you want to invoke the method "on the clock" (e.g. every hour on the hour), you can integrate the following idea with whichever threading mechanism you choose:
The simplest way is to create a background thread that runs something every 60 seconds. A trivial implementation is:
Obviously, this if the "do something" takes a long time, you'll need to accommodate for it in your sleep statement. But this serves as a good approximation.
I think the right way to run a thread repeatedly is the next:
With this code, the function f is executed every 3 seconds within the 10 seconds time.sleep(10). At the end running of thread is canceled.
You could try the threading.Timer class: http://docs.python.org/library/threading.html#timer-objects.