Exponential backoff 指數(shù)避退算法

維基百科的定義

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.

簡(jiǎn)單的 Python 實(shí)現(xiàn),

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}次重試,時(shí)間為u0z1t8os*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()

輸出結(jié)果為

get http response
第1次重試,時(shí)間為0*0.5
get http response
第2次重試,時(shí)間為1*0.5
get http response
第3次重試,時(shí)間為7*0.5
get http response
第4次重試,時(shí)間為4*0.5
get http response
第5次重試,時(shí)間為10*0.5
get http response

設(shè)置的基本避退時(shí)間為 0.5 ,重試次數(shù)為 5

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,942評(píng)論 0 13
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom閱讀 3,229評(píng)論 0 3
  • Cyber-dojo.org是編程操練者的樂園。下面是這個(gè)網(wǎng)站上的43個(gè)編程操練題目,供編程操練愛好者參考。 10...
    程序員吾真本閱讀 1,981評(píng)論 1 2
  • 管弦琴樂_6720閱讀 146評(píng)論 0 2
  • 立冬了,一宵寒比一宵多。天寒加衣,鍛煉身體,提高體質(zhì)。 一說到寒,讓我想起酒來。晚來天欲雪,能飲一杯無?天寒欲雪,...
    天馬行空云飛揚(yáng)閱讀 603評(píng)論 0 1

友情鏈接更多精彩內(nèi)容