Sometimes, we want to run certain code every n seconds with Python.
In this article, we’ll look at how to run certain code every n seconds with Python.
How to run certain code every n seconds with Python?
To run certain code every n seconds with Python, we can use the threading.Timer
class.
For instance, we write
import threading
def printit():
threading.Timer(5.0, printit).start()
print("Hello, World")
printit()
to run the printit
function after 5 seconds.
With threading.Timer(5.0, printit).start()
.
We use printit
as the function to run when creating the Timer
so it’ll run every 5 seconds.
Conclusion
To run certain code every n seconds with Python, we can use the threading.Timer
class.