python?time模塊定時器由淺入深應(yīng)用實(shí)例
引言
在Python中,定時器是一個非常實(shí)用的功能,它可以幫助我們在特定時間后執(zhí)行某段代碼。這在許多應(yīng)用場景中都極為重要,例如數(shù)據(jù)抓取的定時任務(wù)、定期發(fā)送郵件提醒、系統(tǒng)監(jiān)控等。
下面將逐步介紹幾種Python定時器的實(shí)現(xiàn)方式及其應(yīng)用場景。
1. 簡單定時器(time.sleep())
import time
def simple_timer():
print("開始計(jì)時...")
time.sleep(5) # 暫停5秒
print("5秒鐘已過...")
simple_timer()2. 基于threading模塊的定時器
import threading
import time
def timer_function(name):
def function():
print(f"{name} 定時器啟動,等待3秒...")
time.sleep(3)
print(f"{name} 定時器結(jié)束.")
return function
# 創(chuàng)建并啟動定時器
timer1 = threading.Timer(0, timer_function("Timer1"))
timer2 = threading.Timer(2, timer_function("Timer2"))
timer1.start()
timer2.start()
# 主線程等待所有定時器結(jié)束
while threading.active_count() > 1:
time.sleep(1)3. 使用asyncio模塊實(shí)現(xiàn)異步定時器
import asyncio
async def timer coroutine(seconds):
print(f"開始計(jì)時,等待{seconds}秒...")
await asyncio.sleep(seconds)
print(f"{seconds}秒鐘已過...")
async def main():
task1 = asyncio.create_task(timer_coroutine(3))
task2 = asyncio.create_task(timer_coroutine(5))
await task1
await task2
asyncio.run(main())4. 高級定時任務(wù)調(diào)度庫APScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
def job():
print("定時任務(wù)觸發(fā):現(xiàn)在是 %s" % datetime.now())
scheduler = BlockingScheduler()
scheduler.add_job(job, 'interval', minutes=1)
scheduler.start()5. 使用schedule第三方庫(簡單易用,適合定時任務(wù)調(diào)度)
import schedule
import time
def job():
print("定時任務(wù)觸發(fā):現(xiàn)在是 %s" % datetime.now())
# 每天凌晨3點(diǎn)執(zhí)行job函數(shù)
schedule.every().day.at("03:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)6. 使用concurrent.futures模塊結(jié)合threading.Timer實(shí)現(xiàn)多線程定時任務(wù)管理
import concurrent.futures
import threading
import time
def timer_function(name, seconds):
def function():
print(f"{name} 定時器啟動,等待{seconds}秒...")
time.sleep(seconds)
print(f"{name} 定時器結(jié)束.")
return function
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
future1 = executor.submit(threading.Timer(0, timer_function("Timer1", 3)).start)
future2 = executor.submit(threading.Timer(2, timer_function("Timer2", 5)).start)
concurrent.futures.wait([future1, future2])總結(jié)
以上就是從簡單到復(fù)雜的Python定時器實(shí)現(xiàn)方式及其應(yīng)用場景。根據(jù)實(shí)際需求和項(xiàng)目規(guī)模,你可以選擇適合自己的定時器方案。簡單的定時可以通過time.sleep()完成,對于更復(fù)雜的定時任務(wù),可以利用Python的多線程或多進(jìn)程能力,或者利用異步IO來提高程序效率。而當(dāng)需要進(jìn)行復(fù)雜的定時任務(wù)調(diào)度時,諸如APScheduler這樣的第三方庫則能提供強(qiáng)大且靈活的解決方案。
以上就是python time模塊定時器由淺入深應(yīng)用實(shí)例的詳細(xì)內(nèi)容,更多關(guān)于python time定時器模塊的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python 在 VSCode 中使用 IPython Kernel 的方法詳解
這篇文章主要介紹了Python 在 VSCode 中使用 IPython Kernel 的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
Python報錯TypeError: tuple indices must be
在Python編程過程中,我們經(jīng)常會遇到各種各樣的報錯信息,其中,“TypeError: tuple indices must be integers or slices, not str”這個報錯,對于很多開發(fā)者來說,可能既熟悉又陌生,今天,我們就來深入探討一下這個報錯,看看它是如何產(chǎn)生的,以及如何快速有效地解決它2025-01-01
Python使用wxPython和PyMuPDF實(shí)現(xiàn)合并PDF文檔
處理大量的PDF文檔可能會變得復(fù)雜和耗時,但是,使用Python編程和一些強(qiáng)大的庫,可以使這個任務(wù)變得簡單而高效,下面我們就來看看Python如何使用wxPython和PyMuPDF合并PDF文檔并自動復(fù)制到剪貼板吧2023-11-11
python中的TCP(傳輸控制協(xié)議)用法實(shí)例分析
這篇文章主要介紹了python中的TCP(傳輸控制協(xié)議)用法,結(jié)合完整實(shí)例形式分析了Python基于TCP協(xié)議的服務(wù)器端與客戶端相關(guān)實(shí)現(xiàn)技巧及操作注意事項(xiàng),需要的朋友可以參考下2019-11-11
pytorch 如何使用amp進(jìn)行混合精度訓(xùn)練
這篇文章主要介紹了pytorch 使用amp進(jìn)行混合精度訓(xùn)練的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python實(shí)現(xiàn)圖片指定位置加圖片水?。ǜ絇yinstaller打包exe)
這篇文章主要介紹了Python實(shí)現(xiàn)圖片指定位置加圖片水印,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

