首頁 >後端開發 >Python教學 >如何定期執行Python函數?

如何定期執行Python函數?

Patricia Arquette
Patricia Arquette原創
2024-12-23 18:07:14477瀏覽

How Can I Execute a Python Function Periodically?

在Python 中定期執行函數

當需要以固定時間間隔重複執行函數時,開發人員通常會尋求類似於Objective 的可靠方法C 的NSTimer 或JavaScript 的setTimeout。在這種情況下,類似於獨立於使用者的 cron 腳本的解決方案成為一種有吸引力的選擇。

要在 Python 中實現此目的,可以考慮以下方法:

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

但是,此程式碼可能會出現不可預見的問題。為了避免這些問題,請考慮使用 sched 模組,這是一個通用事件調度程式。以下範例示範了其用法:

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()

或者,如果您的應用程式使用 asyncio、trio、tkinter 等事件循環庫,您可以使用它們提供的方法直接安排任務。

以上是如何定期執行Python函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn