python:waitfor轮询

发布时间:2019-09-21 10:59:30编辑:auto阅读(2067)

    有时候需要等待一个时间不确定的事件的发生。如果直接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)

    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秒中内成功返回

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


关键字