Python3.x下實(shí)現(xiàn)定時(shí)任務(wù)的方式有很多種方式。
一、循環(huán)sleep:
最簡(jiǎn)單的方式,在循環(huán)里放入要執(zhí)行的任務(wù),然后sleep一段時(shí)間再執(zhí)行。缺點(diǎn)是,不容易控制,而且sleep是個(gè)阻塞函數(shù)
def timer(n):?
? ? '''''
? ? 每n秒執(zhí)行一次
? ? '''while True:? ?
? ? ? ? print(time.strftime('%Y-%m-%d %X',time.localtime()))? ?
? ? ? ? yourTask()? # 此處為要執(zhí)行的任務(wù)? ? time.sleep(n)
二、threading的Timer:
例如:5秒后執(zhí)行
def printHello():?
? ? print("start" )
Timer(5, printHello).start()
例如:間隔5秒執(zhí)行一次
def printHello():?
? ? print("start" )
? ? timer = threading.Timer(5,printHello)
? ? timer.start()
? if__name__=="__main__":?
? ? printHello()?
例如:兩種方式組合用,5秒鐘后執(zhí)行,并且之后間隔5秒執(zhí)行一次
def printHello():?
? ? print("start")?
? ? timer = threading.Timer(5,printHello)
? ? timer.start()
? if__name__=="__main__":?
? ? timer = threading.Timer(5,printHello)
? ? timer.start()
三、sched模塊:
sched是一種調(diào)度(延時(shí)處理機(jī)制)。
import time? import os? import sched?
? # 初始化sched模塊的scheduler類? # 第一個(gè)參數(shù)是一個(gè)可以返回時(shí)間戳的函數(shù),第二個(gè)參數(shù)可以在定時(shí)未到達(dá)之前阻塞。? schedule = sched.scheduler(time.time, time.sleep)?
? # 被周期性調(diào)度觸發(fā)的函數(shù)? def execute_command(cmd, inc):?
? ? print('執(zhí)行主程序')
? ? '''''
? ? 終端上顯示當(dāng)前計(jì)算機(jī)的連接情況
? ? '''?
? ? os.system(cmd)?
? ? schedule.enter(inc, 0, execute_command, (cmd, inc))?
? defmain(cmd, inc=60):?
? ? # enter四個(gè)參數(shù)分別為:間隔事件、優(yōu)先級(jí)(用于同時(shí)間到達(dá)的兩個(gè)事件同時(shí)執(zhí)行時(shí)定序)、被調(diào)用觸發(fā)的函數(shù),? # 給該觸發(fā)函數(shù)的參數(shù)(tuple形式)? ? ? schedule.enter(0, 0, execute_command, (cmd, inc))?
? ? schedule.run()?
? # 每60秒查看下網(wǎng)絡(luò)連接情況? if__name__=='__main__':?
? ? main("netstat -an", 60)
四、定時(shí)框架APScheduler:
APScheduler是基于Quartz的一個(gè)Python定時(shí)任務(wù)框架。提供了基于日期、固定時(shí)間間隔以及crontab類型的任務(wù),并且可以持久化任務(wù)。
需要先安裝apscheduler庫(kù),cmd窗口命令:pip install apscheduler
簡(jiǎn)單的間隔時(shí)間調(diào)度代碼:
fromdatetimeimport datetimeimport timeimport osfromapscheduler.schedulers.backgroundimport BackgroundSchedulerdef tick():
? ? print('Tick! The time is: %s'% datetime.now())if__name__=='__main__':
? ? scheduler = BackgroundScheduler()
? ? # 間隔3秒鐘執(zhí)行一次scheduler.add_job(tick,'interval', seconds=3)
? ? # 這里的調(diào)度任務(wù)是獨(dú)立的一個(gè)線程? ? scheduler.start()
? ? print('Press Ctrl+{0} to exit'.format('Break'ifos.name =='nt'else'C'))
? ? try:
? ? ? ? # 其他任務(wù)是獨(dú)立的線程執(zhí)行while True:
? ? ? ? ? ? time.sleep(2)
? ? ? ? ? ? print('sleep!')
? ? except (KeyboardInterrupt, SystemExit):
? ? ? ? scheduler.shutdown()
? ? ? ? print('Exit The Job!')
五、定時(shí)框架Celery:
非常強(qiáng)大的分布式任務(wù)調(diào)度框架;
需要先安裝Celery庫(kù),cmd窗口命令: pip install?Celery
六、定時(shí)框架RQ:
基于Redis的作業(yè)隊(duì)列工具,優(yōu)先選擇APScheduler定時(shí)框架;
七、使用windows的定時(shí)任務(wù):
可以將所需要的Python程序打包成exe文件,然后在windows下設(shè)置定時(shí)執(zhí)行。
八、Linux的定時(shí)任務(wù)(Crontab):
在Linux下可以很方便的借助Crontab來(lái)設(shè)置和運(yùn)行定時(shí)任務(wù)。進(jìn)入Crontab文件編輯頁(yè)面,設(shè)置時(shí)間間隔,使用一些shell命令來(lái)運(yùn)行bash腳本或者是Python腳本,保存后Linux會(huì)自動(dòng)按照設(shè)定的時(shí)間來(lái)定時(shí)運(yùn)行程序。