Skip to content

Instantly share code, notes, and snippets.

@purple4reina
Forked from ChrisTM/throttle.py
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save purple4reina/589ee2499ad04683f855 to your computer and use it in GitHub Desktop.
Save purple4reina/589ee2499ad04683f855 to your computer and use it in GitHub Desktop.
class throttle(object):
"""
Decorator that prevents a function from being called more than once every
time period. If called too soon, RuntimeError is raised.
To create a function that cannot be called more than once a minute:
@throttle(minutes=1)
def my_fun():
pass
"""
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
if time_since_last_call > self.throttle_period:
self.time_of_last_call = now
return fn(*args, **kwargs)
else:
raise RuntimeError(
'Function {} called too soon!'.format(fn.__name__)
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment