欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python 輪詢執(zhí)行某函數(shù)的2種方式

 更新時間:2020年05月03日 14:54:21   作者:liuxiang15  
這篇文章主要介紹了python 輪詢執(zhí)行某函數(shù)的2種方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

目標(biāo):python中每隔特定時間執(zhí)行某函數(shù)

方法1:使用python的Thread類的子類Timer,該子類可控制指定函數(shù)在特定時間后執(zhí)行一次:

所以為了實現(xiàn)多次定時執(zhí)行某函數(shù),只需要在一個while循環(huán)中多次新建Timer即可。

from threading import Timer
import time
 
def printHello():
 print ("Hello")
 print("當(dāng)前時間戳是", time.time())
 
def loop_func(func, second):
 #每隔second秒執(zhí)行func函數(shù)
 while True:
  timer = Timer(second, func)
  timer.start()
  timer.join()
 
loop_func(printHello, 1)

運行結(jié)果如下:

Hello
當(dāng)前時間戳是 1569224253.1897497
Hello
當(dāng)前時間戳是 1569224254.1911764
Hello
當(dāng)前時間戳是 1569224255.1924803
Hello
當(dāng)前時間戳是 1569224256.1957717
Hello
當(dāng)前時間戳是 1569224257.1964536
……

方法2:使用time模塊的sleep函數(shù)可以阻塞程序執(zhí)行

import time
 
def printHello():
 print ("Hello")
 print("當(dāng)前時間戳是", time.time())
 
def loop_func(func, second):
 # 每隔second秒執(zhí)行func函數(shù)
 while True:
  func()
  time.sleep(second)
 
loop_func(printHello, 1)

運行結(jié)果如下:

Hello
當(dāng)前時間戳是 1569224698.5843027
Hello
當(dāng)前時間戳是 1569224699.5843854
Hello
當(dāng)前時間戳是 1569224700.5870178
Hello
當(dāng)前時間戳是 1569224701.5881224
Hello
當(dāng)前時間戳是 1569224702.588771
Hello
當(dāng)前時間戳是 1569224703.5896
Hello
當(dāng)前時間戳是 1569224704.5902
……

總結(jié):感覺方法2更節(jié)約資源,因為同樣使用了while循環(huán),方法2沒有生成多余的線程,但是方法1會生成很多的線程

以上這篇python 輪詢執(zhí)行某函數(shù)的2種方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論