Home >Backend Development >Python Tutorial >How to Execute a Function at Regular Intervals in Python?
Initial Query:
How can one execute a specific function at regular intervals, such as every 10 seconds?
Solution Using Timer:
To address this issue, consider utilizing Python's Timer class. Within the target function, instantiate a new Timer and configure it to call the same function after the desired time interval.
Implementation Example:
The following Python code exemplifies this approach:
import time, threading def foo(): print(time.ctime()) threading.Timer(10, foo).start() foo()
By calling itself at the end of each interval, the function ensures continuous execution without blocking other tasks. The output of the program might resemble:
Thu Dec 22 14:46:08 2011 Thu Dec 22 14:46:18 2011 Thu Dec 22 14:46:28 2011 Thu Dec 22 14:46:38 2011
Benefits of Timer-Based Scheduling:
The above is the detailed content of How to Execute a Function at Regular Intervals in Python?. For more information, please follow other related articles on the PHP Chinese website!