Home >Backend Development >Python Tutorial >How Can I Execute a Python Function Periodically?

How Can I Execute a Python Function Periodically?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 18:07:14463browse

How Can I Execute a Python Function Periodically?

Executing a Function Periodically in Python

When tasked with executing a function repeatedly at fixed intervals, developers often seek a reliable method similar to Objective C's NSTimer or JavaScript's setTimeout. In this context, a solution that resembles a user-independent cron script emerges as an attractive option.

To achieve this in Python, one might consider the following approach:

while True:
    # Code executed here
    time.sleep(60)

However, this code may present unforeseen issues. To circumvent these, consider utilizing the sched module, a general-purpose event scheduler. The following example demonstrates its usage:

import sched, time

def do_something(scheduler):
    # schedule the next call first
    scheduler.enter(60, 1, do_something, (scheduler,))
    print("Doing stuff...")
    # then do your stuff

my_scheduler = sched.scheduler(time.time, time.sleep)
my_scheduler.enter(60, 1, do_something, (my_scheduler,))
my_scheduler.run()

Alternatively, if your application employs an event loop library like asyncio, trio, tkinter, or others, you can directly schedule tasks using their provided methods.

The above is the detailed content of How Can I Execute a Python Function Periodically?. 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