【问题标题】:Python: Rate Limit Multiple Executions of ScriptPython:速率限制脚本的多次执行
【发布时间】:2018-05-28 05:28:11
【问题描述】:

我正在尝试找到一种方法来限制单个线程。多次调用同一个脚本,将后续执行排队或限制在定义的参数范围内。

我发现了很多多处理和多线程解决方案,但这些都适用于脚本的单次执行。对于 same 脚本的单独执行,我不确定如何处理此问题。

我的目标是将线程执行次数限制为每秒二十 (20) 个。等待或排队后续执行,并根据 FIFO 继续处理。

为了进行测试,我们将约束设置为每分钟三 (3) 个。不知道从哪里开始,只是将rate_limit() 显示为占位符。

import time

rate = 60
limit = 3

ts = time.time()

def single_task():
    print ts

rate_limit(single_task())

多次执行的结果应如下所示:

session_1$ ./script.py 
1527483557.76

session_2$ ./script.py 
1527483558.26

session_3$ ./script.py 
1527483559.03

session_4$ ./script.py
hang on a minute... 
1527483560.57 

session_5$ ./script.py 
hang on a minute... 
1527483561.92

【问题讨论】:

    标签: python rate-limiting


    【解决方案1】:

    我遇到了类似的问题,并编写了一个小 Python 包 (mp_throttle) 来限制和监控多个线程或进程。您可以通过pip install mp_throttle 安装它。您可以使用速率限制对其进行实例化,并将节流对象处理到您的线程。然后使用.await_fuel()根据限制阻塞你的线程。

    import mp_throttle
    import threading
    import time
    
    def single_task(throttle):
        while not throttle.kill_flag.is_set():
            throttle.await_fuel()
            print("{}: executed at: {}".format(threading.currentThread().name, time.time()))
        return
    
    throttle = mp_throttle.Throttle(3,60)
    
    for i in range(5):
        t = threading.Thread(target=single_task, args=(throttle,), daemon=True)
        t.start()
    
    throttle.start()
    time.sleep(40)
    throttle.stop()
    

    这将输出如下内容:

    Thread-1: executed at: 1534428994.0086124
    Thread-2: executed at: 1534429014.013284
    Thread-3: executed at: 1534429034.0338206
    

    根据任务类型(定期与不定期执行时间)、您的系统(最短睡眠时间和睡眠准确性)和速率(更高的速率不太准确),可能需要进行一些设置和校准。请查看docs 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      相关资源
      最近更新 更多