目录

justbackoff Build Status codecov

A simple backoff algorithm for Python 3.7+.

Install

$ pip install justbackoff

Usage

Backoff is a counter. It starts at min_ms. After every call to duration(), it is multiplied by factor. It is capped at max_ms. It returns to min_ms on every call to reset(). jitter adds randomness (see below).


Simple example

from justbackoff import Backoff

b = Backoff(min_ms=100, max_ms=10000, factor=2, jitter=False)

print(b.duration())
print(b.duration())
print(b.duration())

print("Reset!")
b.reset()

print(b.duration())
0.1
0.2
0.4
Reset!
0.1

Example using socket package

import socket
import time

from justbackoff import Backoff


sock = socket.socket()
b = Backoff()

while True:
    try:
        sock.connect(("127.0.0.1", 1337))
    except Exception as e:
        d = b.duration()
        print("{}, reconnecting in {} seconds".format(e, d))
        time.sleep(d)
        continue

    b.reset()
    sock.send("Hello, world!")
    sock.close()

Example using jitter

Enabling jitter adds some randomization to the backoff durations. See Amazon’s writeup of performance gains using jitter. Seeding is not necessary but doing so gives repeatable results.

import random

from justbackoff import Backoff

b = Backoff(min_ms=100, max_ms=10000, factor=2, jitter=True)

random.seed(42)

print(b.duration())
print(b.duration())
print(b.duration())

print("Reset!")
b.reset()

print(b.duration())
print(b.duration())
print(b.duration())
0.1
0.102501075522
0.182508795511
Reset!
0.1
0.173647121416
0.303009846227

Credits

Ported from Go backoff

关于

为网络请求或任务执行提供 backoff/retry 策略。

58.0 KB
邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9 京公网安备 11010802032778号