我想在 Python 上每 60 秒执行一次函数,但我不想同时被阻塞。
如何异步执行?
import threading
import time
def f():
print("hello world")
threading.Timer(3, f).start()
if __name__ == '__main__':
f()
time.sleep(20)
使用此代码,函数 f 在 20 秒 time.time 内每 3 秒执行一次。 最后它给出了一个错误,我认为这是因为 threading.timer 没有被取消。
如何取消?
提前致谢!
最佳答案
你可以试试 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()
关于python - 如何在 Python 中每 60 秒异步执行一次函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2223157/