Created
May 27, 2019 01:16
-
-
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
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
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) | |
# |
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
##Original Text
https://stackoverflow.com/a/49801719
If you want to do this without blocking your remaining code, you can use this to let it run in its own thread: