Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rate-limiting utility for tracing and such
#!/usr/bin/env python3
from time import monotonic
class periodically:
def __init__(self, interval):
self.interval = interval
self._previous = None
def __enter__(self):
if self._previous is not None:
raise RuntimeError
self._previous = monotonic()
return self
def __bool__(self):
if self._previous is None:
raise RuntimeError
now = monotonic(); elapsed = now - self._previous
if elapsed >= self.interval:
self._previous = now - elapsed % self.interval
return True
else:
return False
def __exit__(self, exc_type, exc_value, exc_tb):
if self._previous is None:
raise RuntimeError
self._previous = None
if __name__ == '__main__': # test and demonstration
from time import sleep
with periodically(2) as trace:
start = monotonic()
for i in range(20):
sleep(.75)
if trace: print(i, monotonic() - start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment