python中定時器的實現(xiàn)方式
在進行大小的程序任務布置時,我們需要某一任務自己執(zhí)行時,會選擇給它設置固定的時間,這時候定時器的作用就顯現(xiàn)出來了。在python中有很多實現(xiàn)定時的方法,本篇要介紹的是Timer和APScheduler,前者是一種函數(shù),后者是框架。下面就python中定時器實現(xiàn)的兩種方法帶來詳細介紹。
1.Timer
threading模塊中的Timer是一個非阻塞函數(shù),比sleep好一點,不過依然無法固定時間執(zhí)行。
fromdatetimeimportdatetime
fromthreadingimportTimer
#打印時間函數(shù)
defprint_time(inc):
print(datetime.now().strftime("%Y-%m-%d%H:%M:%S"))
"""
Timer的參數(shù)說明
inc:表示時間間隔
print_time:執(zhí)行的函數(shù)
(inc,):傳遞給執(zhí)行函數(shù)的參數(shù)
"""
t=Timer(inc,print_time,(inc,))
t.start()
print_time(2)
2.APScheduler
APScheduler是一個Python定時任務框架,使用起來十分方便。提供了基于日期,固定時間間隔及crontab類型的任務,并且可以持久化任務,并以daemon方式運行應用。
fromapscheduler.schedulers.blockingimportBlockingScheduler
fromdatetimeimportdatetime
defjob():
print(datetime.now().strftime('%Y-%m-%d%H:%M:%S'))
if__name__=="__main__":
scheduler=BlockingScheduler()
scheduler.add_job(job,'interval',seconds=5)
scheduler.start()
以上就是python中定時器的實現(xiàn)方式,一般來說大家會使用timer函數(shù)多一些。當然框架的方法,大家感興趣的話也可以多加嘗試一下。更多Python學習教程請關(guān)注IT培訓機構(gòu):千鋒教育。