Created
December 4, 2017 18:34
-
-
Save brandon-braner/6833f98f81a193a7605d1f31ae6ba827 to your computer and use it in GitHub Desktop.
Simple function to rate limit message printing
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
def print_message(message): | |
""" | |
Function to limit the printing of messages | |
This will limit the printing of messages to amount per second | |
:param message: | |
:return: | |
""" | |
window = 1 | |
max_messages = 5 | |
message_count = 0 | |
last_called = int(time.time()) | |
for i in range(0, 100): | |
time.sleep(.5) | |
elapsed = int(time.time()) - last_called | |
if elapsed - window >= window or message_count > max_messages: | |
print("to many messages in allowed time window") | |
# reset message count to 0 | |
message_count = 0 | |
time_to_wait = elapsed - window | |
time.sleep(int(time_to_wait)) | |
# reset last called, needs to stay after sleep or probably get | |
# stuck in a infinite loop | |
last_called = int(time.time()) | |
message_count = message_count + 1 | |
print(message) | |
print_message('test') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment