Home >Backend Development >Python Tutorial >How to Execute a Function at Regular Intervals in Python?

How to Execute a Function at Regular Intervals in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 05:28:02353browse

How to Execute a Function at Regular Intervals in Python?

Scheduling Periodic Tasks with Precision

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:

  • Precision: The function execution occurs at specified intervals, even under heavy system load.
  • Non-Blocking: It allows other operations to proceed without waiting for the periodic function to complete.
  • Thread Management: The Timer class handles thread creation and management, simplifying the scheduling process.

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!

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