Home  >  Article  >  Backend Development  >  How to Execute a Function Periodically in Windows Using the Timer Class?

How to Execute a Function Periodically in Windows Using the Timer Class?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 22:08:03424browse

How to Execute a Function Periodically in Windows Using the Timer Class?

Executing Periodic Actions

Executing specific functions at regular intervals is a common task in programming. In Windows, there are multiple methods to achieve this, one of which involves utilizing the Timer class.

To execute a function, such as foo(), every 10 seconds, the following approach can be implemented:

  1. Create a Timer Object: Within the foo() function, create a Timer instance and configure it to invoke foo() after the desired interval (e.g., 10 seconds).
  2. Start the Timer: Call the start() method on the Timer object to initiate the execution.
import time, threading

def foo():
    print(time.ctime())
    # Create a Timer to call foo() again after 10 seconds
    threading.Timer(10, foo).start()

foo()
  1. Continuous Execution: The Timer class creates a separate thread to execute foo(), allowing the function to run continuously without blocking the main program.
  2. Output: As a demonstration, the example provided prints the current time every 10 seconds.

The above is the detailed content of How to Execute a Function Periodically in Windows Using the Timer Class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn