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

Mary-Kate Olsen
Release: 2024-11-06 22:08:03
Original
423 people have browsed it

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()
Copy after login
  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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!