Home > Article > Backend Development > How to Execute a Function Every 10 Seconds in Windows Using a Timer Object?
Executing specific functions at regular intervals is a common task in programming. One such scenario is the requirement to execute a function called foo() every 10 seconds. Various programming environments offer different mechanisms to achieve this repetition.
In Windows, one effective approach is to utilize a Timer object. This object creates a new thread that executes the desired function periodically. After completing the function, the Timer object reschedules itself to run the function again after a specified interval.
For instance, consider the following code snippet:
import time, threading def foo(): print(time.ctime()) threading.Timer(10, foo).start() foo()
In this code, the foo() function is called initially. Inside the function, the time.ctime() function is used to print the current time. Subsequently, a Timer object is created that will call the foo() function again after 10 seconds. This Timer object starts a new thread, allowing the program to continue executing other tasks without blocking.
Output:
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
This demonstrates how to create a simple program in Windows that executes a specified function at a specified interval using the Timer object. This technique is particularly useful for scheduling periodic tasks or creating timed events.
The above is the detailed content of How to Execute a Function Every 10 Seconds in Windows Using a Timer Object?. For more information, please follow other related articles on the PHP Chinese website!