Skip to content

Instantly share code, notes, and snippets.

@brandon-braner
Created December 4, 2017 18:34
Show Gist options
  • Save brandon-braner/6833f98f81a193a7605d1f31ae6ba827 to your computer and use it in GitHub Desktop.
Save brandon-braner/6833f98f81a193a7605d1f31ae6ba827 to your computer and use it in GitHub Desktop.
Simple function to rate limit message printing
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