用于停止函数的python计时器



我想构建一个函数,在设定的时间后停止另一个函数。

例如:

def start():
global bol_start
bol_start = True
timer()
if bol_start is True:
"do something until time is over"
def stop():
global bol_start
bol_start = False
sys.exit(0)    
def timer():
"code for actual timer" ?

我想让用户定义时间x工具应该运行start((的时间。时间结束后,它应该调用stop((。

如果函数中有一个连续运行的循环,最简单的机制是每次迭代都测量时间:

import time
def run():
start = time.time()
stop_seconds = 10
while time.time() - start < stop_seconds:
# do something

如果你没有一个循环,或者函数包含耗时的操作,你需要在执行过程中杀死这个函数,就像这里建议的那样:函数调用超时

最新更新