【问题标题】:Start one function repeatedly while another function is executed [duplicate]在执行另一个功能时重复启动一个功能[重复]
【发布时间】:2016-06-08 22:15:30
【问题描述】:
我有一个需要很长时间才能完成的功能。如何在执行长函数时每 X 秒执行另一个函数?
脚本使用 Python 3.4
【问题讨论】:
标签:
python
python-3.x
asynchronous
【解决方案1】:
这是一个非常简单的例子。如果在第一个功能完成后终止第二个功能对您很重要,仍然可以对其进行调整。
import threading, time
def func_long(ev):
# do stuff here
for _ in range(12):
print("Long func still working")
time.sleep(1)
# if complete
ev.set()
def run_func(ev, nsec):
if ev.is_set():
return
print ("Here run periodical stuff")
threading.Timer(nsec, run_func, [ev, nsec]).start()
def main():
ev = threading.Event()
threading.Timer(5.0, run_func, [ev, 5]).start()
func_long(ev)
if __name__=='__main__':
main()