通过func_timeout模块和retrying模块实现python函数超时重试

通过看网上前辈的博客知道两个模块:

func_timeout retrying

这两个模块都是装饰器,第一个能让python函数超时时候抛出一个超时异常,第二个能让python函数异常时候重试

根据这两个模块的功能,把他们用到一起,就能实现函数超时重试的功能

from func_timeout import func_set_timeout
import time
import func_timeout
from retrying import retry

def retry_if_error(exception):
    print("---------------------------")
    return isinstance(exception, func_timeout.exceptions.FunctionTimedOut)

@retry(retry_on_exception=retry_if_error)
@func_set_timeout(3)
def task():
    while True:
        print('hello world')
        time.sleep(1)


if __name__ == '__main__':
    try:
        task()
    except func_timeout.exceptions.FunctionTimedOut:
        raise func_timeout.exceptions.FunctionTimedOut

运行后结果如下:

通过func_timeout模块和retrying模块实现python函数超时重试_第1张图片

你可能感兴趣的:(python,func_timeout,retrying,超时,重试)