前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python:waitfor轮询

python:waitfor轮询

作者头像
py3study
发布2020-01-06 15:15:15
1.3K0
发布2020-01-06 15:15:15
举报
文章被收录于专栏:python3python3

有时候需要等待一个时间不确定的事件的发生。如果直接sleep最大时长,然后判断预期,则严重影响效率。可以改用轮询机制,一旦条件满足,立即返回;反之等到最后超时。

代码语言:javascript
复制
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)

2, 2 0:00:00.001000 2, 3 ==================== 8, 4 0:00:00.002000 8, 5 0:00:00.303000 8, 6 0:00:00.605000 8, 7 0:00:00.907000 8, 8 0:00:01.209000 Traceback (most rece   File "multiver.py"     waitfor(testgetv   File "multiver.py"     raise Exception Exception

第一轮测试,在1秒中内成功返回

第二轮测试,在预定的时间内未得到预期结果,抛出超时异常

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档