亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

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

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

from threading import Timer
import time
 
def printHello():
 print ("Hello")
 print("當(dāng)前時(shí)間戳是", 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)

運(yùn)行結(jié)果如下:

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

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

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

運(yùn)行結(jié)果如下:

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

總結(jié):感覺方法2更節(jié)約資源,因?yàn)橥瑯邮褂昧藈hile循環(huán),方法2沒有生成多余的線程,但是方法1會(huì)生成很多的線程

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

相關(guān)文章

最新評(píng)論