HEX
Server: Apache/2.4.63 (Unix)
System: Linux Synopilou92 4.4.302+ #72806 SMP Mon Jul 21 23:16:00 CST 2025 x86_64
User: pilou92 (1026)
PHP: 8.0.30
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()