Python的定時器與線程池


定時器執行循環任務:

 

  • 知識儲備
  1.   Timer(interval, function, args=None, kwargs=None)
  2. interval ===》 時間間隔 單位為s
  3. function ===》 定制執行的函數
  • 使用threading的 Timer 類
  1. start() 為通用的開始執行方法
  2. cancel ()為取消執行的方法
  • 普通單次定時執行
from threading import Timer
import time
# 普通單次定時器
def handle():
print("普通單次定時器 函數被執行");
t1=Timer(interval=1,function=handle);
t1.start();

 

定時循環執行

from threading import Timer
import time
# 循環定時器
def loop_handle():
print("循環定時器定時器 函數被執行");
global t2;
t2=Timer(interval=1,function=loop_handle);
t2.start();

t2=Timer(interval=1,function=loop_handle);
t2.start();

time.sleep(5);# 對主線程停止5s;
t2.cancel(); # t2 在主main 線程阻塞5s t2執行5s

  

線程池技術

 

 

基本概念

  • 在程序啟動時就創建好若干個線程,並保存到內存中 。 當線程啟動並執行完成之后,並不做銷毀處理,而是等待下次再使用。

    i:節約了創建進程 銷毀進程的時間,大大降低進程的開銷

  • 實現
  1. 搶占式:線程池中的線程執行順序不固定。該方式使用 ThreadPoolExecutor的 submit ()方法實現。
    1.       具體執行那個線程是隨機的, 並且執行的函數也可以不一致
    2.   那個線程執行的函數出現了崩潰,不影響整個線程池的其他線程的運行
    3.   使用with 語法 進行簡化操作
  • 非搶占式:線程將按照調用的順序執行 。 此方式使用 ThreadPoolExecutor 的 map ()方法來實現
  1.   每個線程處理的函數都是一致的,一個線程執行的函數崩潰,整體就崩潰

基本code

from concurrent.futures import ThreadPoolExecutor # 導入線程池
import time

def printName(name):
print("名字",name);
time.sleep(2);
nameList=['Tom','jirl','steam'];
# 搶占式線程池
start2=time.time();
with ThreadPoolExecutor(3) as executor:
for i in nameList:# 因為每次執行的函數不一致,所以參數要分開傳遞
executor.submit(printName,i); 
end2=time.time();
print("2 speed:",str(end2-start2));
#非搶占式線程池

 

 


線程數量公式:
公式

 

 

經驗
(1 )初始化一定數量的線程。
( 2 )在多次實驗中遞增或遞減線程數量 ,測試運行性能 。
(3 )確定最憂 的線程數量。

 


免責聲明!

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



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