python開發--Python實現延時操作的幾種方式


1. time.sleep

2. sched.scheduler

3. threading.Timer

4. 借助其他程序

    celery

 redis延時隊列 

在日常的開發中,往往會遇到這樣的需求,需要某一個函數在一段時間之后才執行以達到某種特定的效果。此時,我們就需要某種機制,使一個函數延后執行。接下來簡單介紹一下兩種實現此類效果的方法:
sched
    
import sched,time
def func(a):
  print time.time(),"Hello Sched!",a
print time.time()
s = sched.scheduler(time.time,time.sleep)
# 2為延后時間,1為優先級,func為函數名,("test1",)為函數參數
s.enter(2,1,func,("test1",))
s.enter(2,0,func,("test2",))
s.run()
print time.time()

輸出結果如下:

    1519443179.4
    1519443181.4 Hello Sched! test2
    1519443181.4 Hello Sched! test1
    1519443181.4

從結果可以看出,函數果真延后了2s執行,並且test2比test1先執行,是因為同樣是2s后執行,並且test2的優先級比test1高

timer
    
import threading,time
def func(a):
  print time.time(),"Hello Timer!",a
print time.time()
s = threading.Timer(2,func,("test",))
s.start()
print time.time()

輸出結果如下:

    1519443055.69
    1519443055.69
    1519443057.69 Hello Timer! test

從結果可以看出,函數果真延后了2s執行。

從兩種方式的輸出結果可以看出,timer是異步執行的,並不卡住下面代碼的執行,而sched會等到執行函數完成后才會往下執行。

 

一些參考:https://www.jianshu.com/p/944ae43e2662

https://www.jianshu.com/p/a8c1458998aa

https://segmentfault.com/a/1190000010021748

https://tech.youzan.com/queuing_delay/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM