欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

超时重试注解py版

程序员文章站 2022-05-24 14:30:10
...

      import random

import time
import signal
from retrying import retry
from functools import wraps


def run_timeout(time_out):
    def wrapper(fun):
        @wraps(fun)
        def func(*args, **kwargs):
            def handler(signum, frame):
                raise AssertionError
try:
                signal.signal(signal.SIGALRM, handler)
                signal.alarm(time_out)
                return fun(*args, **kwargs)
            except AssertionError:
                print('timeout')
                return 'timeout'
return func
    return wrapper


n = 0
@retry
@run_timeout(1)
def have_a_try():

    global n
    n += 1
print('try {}'.format(n))
    time.sleep(1)
    if random.randint(0, 10) != 5:
        raise Exception('it is not 5')
    print('it is 5')
相关标签: timeout retry