Home  >  Article  >  Backend Development  >  How to Execute Functions Periodically in Windows?

How to Execute Functions Periodically in Windows?

DDD
DDDOriginal
2024-11-07 20:00:03700browse

How to Execute Functions Periodically in Windows?

Executing Periodic Actions in Windows

Executing a specific function at regular intervals is a common task in programming. In Windows, you need a way to schedule the function's execution repeatedly.

Method:

To execute a function (foo()) every 10 seconds in Windows, a simple and effective approach is to use the Timer class. This class allows you to set a delay and a callback function to be executed when the delay expires.

Implementation:

Within the foo() function, you can create a new Timer object with a delay of 10 seconds and the foo() function as the callback. This Timer will automatically call foo() after the specified interval.

import time, threading

def foo():
    # Do the task
    print(time.ctime())

    # Schedule the next execution
    threading.Timer(10, foo).start()

foo()

Explanation:

  • Creating the Timer in foo() ensures that it will be called repeatedly, as long as the foo() function is being executed.
  • The Timer creates a separate thread to call foo(), allowing you to continue performing other tasks without blocking the main thread.

Sample 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

The above is the detailed content of How to Execute Functions Periodically in Windows?. 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