Skip to content

Instantly share code, notes, and snippets.

@naiquevin
Created June 30, 2015 18:54
Show Gist options
  • Save naiquevin/e93dfcaad46108c53931 to your computer and use it in GitHub Desktop.
Save naiquevin/e93dfcaad46108c53931 to your computer and use it in GitHub Desktop.
Greedy throttling for function calls
import time
from functools import wraps
def throttle_greedy(wait):
def decorator(fn):
state = {'last_call_at': None}
@wraps(fn)
def wrapper(*args, **kwargs):
last_call_at = state.get('last_call_at')
now = long(time.time())
if last_call_at:
diff = now - last_call_at
if diff < wait:
time.sleep(wait - diff)
result = fn(*args, **kwargs)
state['last_call_at'] = long(time.time())
return result
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment