Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 981
aF. Avatar asked Feb 08 '10 16:02

aF.


People also ask

How do you call a function every 5 minutes in Python?

With the help of the Schedule module, we can make a python script that will be executed in every given particular time interval. with this function schedule. every(5). minutes.do(func) function will call every 5 minutes.

How do you call a function continuously in Python?

start() and stop() are safe to call multiple times even if the timer has already started/stopped. function to be called can have positional and named arguments. You can change interval anytime, it will be effective after next run. Same for args , kwargs and even function !

How do you program asynchronous in Python?

We can achieve this behavior through a coroutine object. In Python, we can do this using the async keyword before the function definition. Execution of this coroutine results in a coroutine object.

Does Python run asynchronously?

In Python, there are many ways to execute more than one function concurrently, one of the ways is by using asyncio. Async programming allows you to write concurrent code that runs in a single thread. Note: Asyncio doesn't use threads or multiprocessing to make the program Asynchronous.


2 Answers

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() 
like image 93
David Underhill Avatar answered Nov 04 '22 17:11

David Underhill


The simplest way is to create a background thread that runs something every 60 seconds. A trivial implementation is:

class BackgroundTimer(Thread):       def run(self):       while 1:         Time.sleep(60)         # do something   # ... SNIP ... # Inside your main thread # ... SNIP ...  timer = BackgroundTimer() timer.start() 

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.

like image 38
0xfe Avatar answered Nov 04 '22 18:11

0xfe