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.9311035 now is 1512033157.9316308 | output= test1 1512033155.9311035 now is 1512033157.9316308 | output= test1 1512033155.9311035 now is 1512033158.9322016 | output= test1 1512033155.9311035 now is 1512033159.9316351 | output= test1 1512033155.9311035 1512033159.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.9443169 1512034286.9452875 now is 1512034291.9460146 enter_the_box_time is 1512034286.9443169 now is 1512034296.9461012 enter_the_box_time is 1512034286.9452875 [Finished in 10.2s]
可看出任務和主線程是同步執行,但是后3位又稍有不同,應該是python的多線程並非真正的多線程導致
每天某個時間定時執行任務:
import datetime import time def 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()
4 linux用 crontab