Skip to content

Instantly share code, notes, and snippets.

@johncadengo
Forked from ChrisTM/throttle.py
Last active September 27, 2022 14:09
Show Gist options
  • Save johncadengo/0f54a9ff5b53d10024ed to your computer and use it in GitHub Desktop.
Save johncadengo/0f54a9ff5b53d10024ed to your computer and use it in GitHub Desktop.
Python decorator for throttling function calls. Sleeps until it can be called
class throttle(object):
"""Decorator that prevents a function from being called more than once every
time period.
To create a function that cannot be called more than once a minute, but
will sleep until it can be called:
@throttle(minutes=1)
def foo():
pass
for i in range(10):
foo()
print "This function has run %s times." % i
"""
def __init__(self, seconds=0, minutes=0, hours=0):
self.throttle_period = timedelta(
seconds=seconds, minutes=minutes, hours=hours
)
self.time_of_last_call = datetime.min
def __call__(self, fn):
@wraps(fn)
def wrapper(*args, **kwargs):
now = datetime.now()
time_since_last_call = now - self.time_of_last_call
time_left = self.throttle_period - time_since_last_call
if time_left > timedelta(seconds=0):
time.sleep(time_left.seconds)
self.time_of_last_call = datetime.now()
return fn(*args, **kwargs)
return wrapper
@livni
Copy link

livni commented Sep 27, 2022

Isn't this missing:

import time
from datetime import datetime, timedelta
from functools import wraps

@livni
Copy link

livni commented Sep 27, 2022

in line #29 it should probably be time.sleep(time_left.total_seconds())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment