美文网首页
Exponential backoff 指数避退算法

Exponential backoff 指数避退算法

作者: 七秒钟回忆待续 | 来源:发表于2020-04-19 16:09 被阅读0次

    维基百科的定义

    Example exponential backoff algorithm

    1. When a collision first occurs, send a "Jamming signal" to prevent further data from being sent.
    2. Resend a frame after either 0 seconds or 51.2 μs, chosen at random.
    3. If that fails, resend the frame after either 0 s, 51.2 μs, 102.4 μs, or 153.6 μs.
    4. If that still doesn't work, resend the frame after k · 51.2 μs, where k is a random integer between 0 and 23 − 1.
    5. In general, after the cth failed attempt, resend the frame after k · 51.2 μs, where k is a random integer between 0 and 2c − 1.

    简单的 Python 实现,

    import functools
    import random
    import time
    
    
    def retry(tries, back_off=0.5):
        def _retry(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                max_retries = tries
                result = func(*args, **kwargs)
                while max_retries > 0:
                    if result:
                        return result
                    max_retries -= 1
                    d = random.randint(0, (tries - max_retries) ** 2 - 1)
                    print(f"第{tries - max_retries}次重试,时间为{d}*0.5")
                    time.sleep(d * back_off)
                    result = func(*args, **kwargs)
                return result
    
            return wrapper
    
        return _retry
    
    
    @retry(5)
    def get_response():
        print("get http response")
    
    
    if __name__ == '__main__':
        get_response()
    

    输出结果为

    get http response
    第1次重试,时间为0*0.5
    get http response
    第2次重试,时间为1*0.5
    get http response
    第3次重试,时间为7*0.5
    get http response
    第4次重试,时间为4*0.5
    get http response
    第5次重试,时间为10*0.5
    get http response
    

    设置的基本避退时间为 0.5 ,重试次数为 5

    相关文章

      网友评论

          本文标题:Exponential backoff 指数避退算法

          本文链接:https://www.haomeiwen.com/subject/egnmbhtx.html