在多个操作中使用一个总超时
totaltimeout的Python项目详细描述
在多个操作中使用一个总超时。
正确有效地将一个超时扩展到多个步骤 重新计算等待一段时间后的剩余时间 已经发生,将调整后的超时传递给下一个调用。
安装
pip install totaltimeout
用法
导入Timeout类。
fromtotaltimeoutimportTimeout
在“定时循环”中等待API并重试:
fortime_leftinTimeout(SOME_NUMBER_OF_SECONDS):reply=requests.get(some_flaky_api_url,timeout=time_left)ifreply.status==200:breaktime.sleep(some_retry_delay)
等待多个任务完成:
timeout=Timeout(10.0)my_thread_foo.join(timeout.time_left())my_thread_bar.join(timeout.time_left())my_thread_qux.join(timeout.time_left())# Waits at most ten seconds total for all three threads, but# waits the full ten seconds if *any* thread takes that long.
在“定时循环”的每个迭代中等待多个任务 (结合以上两个例子):
timeout=Timeout(SOME_NUMBER_OF_SECONDS)fortime_leftintimeout:foo.some_work(timeout=time_left)# The first timeout can be *either* be the for loop value or# the ``time_left()`` method. The rest *have to be* the latter.foo.more_work(timeout=timeout.time_left())some_other_work(timeout=timeout.time_left())
高级使用说明
Timeout使用time.monotonic作为默认时间函数, 如果time.monotonic不可用,则返回time.time。
您可以通过将callable作为第二个参数传入来覆盖它。
例如,如果您安装了 monotonic backport:
frommonotonicimportmonotonictimeout=Timeout(10.0,now=monotonic)
任何以秒为单位返回时间作为浮点值的可调用函数 作为接口的一部分支持 兼容性保证。
但是,any可调用函数返回的时间值可以是 相互相减以产生持续时间值,进而可以 相互减去并与零进行比较应该有效,并且 只需要秒,因为python的惯用超时单位 是秒。如果timeout、now和用法一致,则 符合这些标准的选择可能会奏效。