发布时间:2019-09-21 10:59:30编辑:auto阅读(2527)
有时候需要等待一个时间不确定的事件的发生。如果直接sleep最大时长,然后判断预期,则严重影响效率。可以改用轮询机制,一旦条件满足,立即返回;反之等到最后超时。
def waitfor(getter, timeout=3, interval=0.5, *args):
	starttime = datetime.datetime.now()
	while True:
		if getter(args):
			return
		else:
			runtime = datetime.datetime.now() - starttime
			print runtime
			if runtime.seconds >= timeout:
				raise Exception
			time.sleep(interval)
	
current_value = 1	
def testgetval(args):
	wanted_value = args[0]
	global current_value
	current_value += 1
	print '%d, %d' % (wanted_value, current_value)
	return current_value > wanted_value	
		
if __name__ == '__main__':
	waitfor(testgetval, 1, 0.3, 2)
	print '======================='
	waitfor(testgetval, 1, 0.3, 8)第一轮测试,在1秒中内成功返回
第二轮测试,在预定的时间内未得到预期结果,抛出超时异常
上一篇: 2018年,10个最好用的Python集
下一篇: python中3种调用可执行文件.exe
 51251
 50687
 41287
 38108
 32571
 29471
 28335
 23197
 23162
 21489
 1564°
 2284°
 1892°
 1829°
 2144°
 1876°
 2565°
 4298°
 4150°
 2960°