-
-
Save jaredkoontz/8c22f68929898375aecd7d2464ec1b25 to your computer and use it in GitHub Desktop.
Python decorator for throttling function calls.
This file contains hidden or 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
| from datetime import timedelta | |
| from datetime import datetime | |
| import time | |
| class Throttle: | |
| ''' | |
| A way to achieve rate limiting without a decorator. Prevents a function from being called more than once every | |
| time period. | |
| Calls a function every x seconds (or x minutes, hours, etc) depending on the given arguments. | |
| ''' | |
| 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 rate_limit(self, function, *args): | |
| 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 function(*args) | |
| def foo(output): | |
| now = datetime.now() | |
| print '{} at {}'.format(output, now) | |
| def test(): | |
| throttle = Throttle(seconds=15) | |
| for i in range(10): | |
| throttle.rate_limit(foo, 'test') | |
| print 'This function has run {} times.'.format(i) | |
| if __name__ == '__main__': | |
| test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment