Skip to content

Instantly share code, notes, and snippets.

@allanfreitas
Created May 27, 2019 01:16
Show Gist options
  • Save allanfreitas/e2cd0ff49bbf7ddf1d85a3962d577dbf to your computer and use it in GitHub Desktop.
Save allanfreitas/e2cd0ff49bbf7ddf1d85a3962d577dbf to your computer and use it in GitHub Desktop.
the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python
import time, traceback
def every(delay, task):
next_time = time.time() + delay
while True:
time.sleep(max(0, next_time - time.time()))
try:
task()
except Exception:
traceback.print_exc()
# in production code you might want to have this instead of course:
# logger.exception("Problem while executing repetitive task.")
# skip tasks if we are behind schedule:
next_time += (time.time() - next_time) // delay * delay + delay
def foo():
print("foo", time.time())
every(5, foo)
#
@jeppius
Copy link

jeppius commented Mar 27, 2021

how would you stop the periodic task in your code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment