[英]Multi threading functions with locks and delays inside infinite loop in python 3.x
我試圖在無限循環中每隔幾分鍾或幾天運行幾個函數。 這些函數從API調用數據並處理數據(制作數據幀並寫入文件)。
為此,我嘗試while True:
循環的多個函數中使用多線程,每個函數均包含API調用和相關響應的數據處理。 每個函數都有不同的循環延遲,API的呼叫速率限制為每秒1個呼叫。
這是實現我的目標的正確方法嗎?
請提供所有建議,技巧,更正,警告等。很容易找到非常基本的多線程示例,但是很難找到比基本多一點的東西。
這是我的代碼的簡化版本(以演示結構而不是100%正確):
import requests
import time
import threading
#... other imports
api = "https://..."
api_lock = threading.Lock()
def A():
url = "abc"
api_lock.acquire()
response = requests.get(api+url)
time.sleep(1) #to avoid api call limit
api_lock.release()
#processing response (making dataframes and writing to files)
time.sleep(300)
def B():
url = "ghi"
api_lock.acquire()
response = requests.get(api+url)
time.sleep(1)
api_lock.release()
#processing response (making dataframes and writing to files)
time.sleep(180)
def C():
url = "jkl"
api_lock.acquire()
response = requests.get(api+url)
time.sleep(1)
api_lock.release()
#processing response (making dataframes and writing to files)
time.sleep(86400) # 1 day
def combined():
t_A = threading.Thread(target = A)
t_A.start()
if t_A.is_alive() == False:
print('Will check A again in 5 min...')
t_B = threading.Thread(target = B)
t_B.start()
if t_B.is_alive() == False:
print('Will check B again in 3 min...')
for i in range (50):
t_C = threading.Thread(target = C,args=(i,))
t_C.start()
if t_C.is_alive() == False:
print('Will check C again tomorrow...')
while True:
combined()
您缺少線程獨立於啟動它們的主線程運行的想法。 因此,一旦main執行.start()調用,它便可以在啟動后移至下一條語句,而通過線程調用的函數將並行運行。 結果是您永遠不會在主線程中等待,並且由於while true循環而使生成的線程一直運行而沒有延遲。 只需生成線程ONCE,然后在每個函數中循環,以使函數延遲成為其循環的一部分。 希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.