aF.*_*aF. 58 python asynchronous function call
我想在Python上每60秒执行一次函数,但我不希望同时被阻塞.
我该如何异步进行?
import threading
import time
def f():
print("hello world")
threading.Timer(3, f).start()
if __name__ == '__main__':
f()
time.sleep(20)
Run Code Online (Sandbox Code Playgroud)
使用此代码,函数f在20秒time.time内每3秒执行一次.最后它给出了一个错误,我认为这是因为threading.timer还没有被取消.
我该如何取消?
提前致谢!
Dav*_*ill 100
您可以尝试使用threading.Timer类: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()
Run Code Online (Sandbox Code Playgroud)
最简单的方法是创建一个后台线程,每 60 秒运行一次。一个简单的实现是:
import time
from threading import Thread
class BackgroundTimer(Thread):
def run(self):
while 1:
time.sleep(60)
# do something
# ... SNIP ...
# Inside your main thread
# ... SNIP ...
timer = BackgroundTimer()
timer.start()
Run Code Online (Sandbox Code Playgroud)
显然,如果“做某事”需要很长时间,那么您需要在睡眠声明中适应它。但是,60 秒是一个很好的近似值。