HEX
Server: Apache/2.2.34 (Unix) mod_fastcgi/mod_fastcgi-SNAP-0910052141
System: Linux Kou-Etsu-Dou 4.4.59+ #25556 SMP PREEMPT Thu Mar 4 18:03:46 CST 2021 x86_64
User: hosam (1026)
PHP: 7.2.29
Disabled: NONE
Upload Files
File: /volume1/@appstore/HyperBackup/addon/openstack_swift/python/swiftclient/throttler.py
import threading
import time

class Throttler:
    def __init__(self, capacity, lock):
        self.activated = False
        self.capacity = capacity
        self.remain = 0
        self.lock = lock

    def refill(self):
        self.remain = self.capacity
        if self.activated:
            timer_thread = threading.Timer(1.0, self.refill)
            timer_thread.daemon = True
            timer_thread.start()

    def activate(self):
        self.activated = True
        self.refill()

    def deactivate(self):
        self.activated = False

    def consume(self, size):
        self.lock.acquire()
        while size > self.remain:
            time.sleep(0.01)
        self.remain -= size
        self.lock.release()

if __name__ == '__main__':
    lock = threading.Lock()
    tt = Throttler(1024 * 1024, lock)
    tt.activate()
    start_time = time.time()
    while True:
        tt.consume(65535)
        # do something here
        if time.time() - start_time > 60:
            break
    tt.deactivate()