在继续 while 循环之前运行定时函数



>im 尝试在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')

最新更新