Created
June 30, 2015 18:54
-
-
Save naiquevin/e93dfcaad46108c53931 to your computer and use it in GitHub Desktop.
Greedy throttling for function calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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