標籤:缺點 任務 sleep pytho ring 表示 threading 線程 非阻塞
1 time.sleep
import time
for i in range(5):
print(i)
time.sleep(10)
2 用shed
import time import sched schedule = sched.scheduler ( time.time, time.sleep ) def func(string1,float1): print("now is",time.time()," | output=",string1,float1) print(time.time())schedule.enter(2,0,func,("test1",time.time())) schedule.enter(2,0,func,("test1",time.time())) schedule.enter(3,0,func,("test1",time.time())) schedule.enter(4,0,func,("test1",time.time())) schedule.run() print(time.time())
其中func中放要執行的函數,用schedule.enter加入要執行的函數,裡面的第一個參數是順延強制的時間,用sched.scheduler進行初始化
1512033155.9311035now is 1512033157.9316308 | output= test1 1512033155.9311035now is 1512033157.9316308 | output= test1 1512033155.9311035now is 1512033158.9322016 | output= test1 1512033155.9311035now is 1512033159.9316351 | output= test1 1512033155.93110351512033159.9316351[Finished in 4.2s]
上面是執行結果,缺點是任務隊列是阻塞型,即schedule裡的任務不執行完,後面的主線程就不會執行
3 用threading裡的timer,實現非阻塞型,即主線程要任務同時執行
import time from threading import Timer def print_time( enter_time ): print "now is", time.time() , "enter_the_box_time is", enter_time print time.time() Timer(5, print_time, ( time.time(), )).start() Timer(10, print_time, ( time.time(), )).start() print time.time()
執行結果:
1512034286.94431691512034286.9452875now is 1512034291.9460146 enter_the_box_time is 1512034286.9443169now is 1512034296.9461012 enter_the_box_time is 1512034286.9452875[Finished in 10.2s]
可看出任務和主線程是同步執行,但是後3位又稍有不同,應該是python的多線程並非真正的多線程導致
每天某個時間定時執行任務:
import datetimeimport timedef doSth(): print(‘test‘) # 假裝做這件事情需要一分鐘 time.sleep(60)def main(h=0, m=0): ‘‘‘h表示設定的小時,m為設定的分鐘‘‘‘ while True: # 判斷是否達到設定時間,例如0:00 while True: now = datetime.datetime.now() # 到達設定時間,結束內迴圈 if now.hour==h and now.minute==m: break # 不到時間就等20秒之後再次檢測 time.sleep(20) # 做正事,一天做一次 doSth()main()
python定時執行方法