[英]Run timed function before continuing with the while loop
我试图在while loop
使用threading.timer
调用一个函数,我希望它先停止while循环,然后等待直到定时器中的函数启动,然后继续循环。 但是似乎我的期望与我的代码不一致。 在此我将提供帮助。 感谢名单
码:
import threading
def test():
print("Updating....")
def cont():
arg = raw_input("Update File(y/n): ")
print(arg)
if arg == 'y':
return True
else:
return False
def printit():
while cont():
print("Auto update every 10 sec!")
threading.Timer(10.0, test).start()
print('now its false')
printit()
我希望在再次运行循环之前先调用test()
。
当前的行为是预期的,因为您正在使用threading
库。 当您执行threading.Timer(10.0, test).start()
您将启动一个新线程,该线程将等待10秒钟,然后启动test
。 但是由于它是一个新线程,而不是您运行循环的基本线程,因此不会等待它-这就是异步编程中发生的情况。
如果希望代码以同步方式运行,则可以使用简单的time.sleep
来实现:
import time
def printit():
while cont():
print("Auto update every 10 sec!")
time.sleep(10.0)
test()
print('now its false')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.