嗨,我有多個使用執行緒運行的函式。我想知道在運行多個執行緒時如何處理不影響正在運行的其他執行緒的錯誤。當一個函式中斷時,其他函式也會停止。除了每個時間表外,我是否都嘗試過?或者,還有更好的方法?
目前的結構是這樣的。
#--------------------------------------------------------------------------run_threaded function
def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start()
#------------------------------------------------------------------------scheduler function
#scheduler
print('scheduler is starting')
schedule.every().day.at('06:30').do(run_threaded,lambda:functionA())
schedule.every().day.at('06:30').do(run_threaded,lambda:functionB())
schedule.every().day.at('06:30').do(run_threaded,lambda:functionC())
schedule.every().day.at('06:30').do(run_threaded,lambda:functionD())
schedule.every().day.at('06:30').do(run_threaded,lambda:fucntionE())
schedule.every().day.at('22:00').do(lambda:email())
schedule.every().day.at('22:15').do(lambda:writeFile())
while True:
schedule.run_pending()
sleep(1)
uj5u.com熱心網友回復:
我想首先說明[Python.Docs]: threading - 基于執行緒的并行性實際上并不執行多執行緒(在多個CPU上),但它更像是一個(蹩腳的)解決方法(gainarie),因為GIL。
如果您真的想要并行執行,請使用[Python.Docs]: multiprocessing - Process-based parallelism。
但即使上述情況不正確,您的代碼中實際上也沒有多執行緒。根據[ReadTheDocs.Schedule]: Schedule(如果這是您正在使用的模塊),這些方法(如do)期望一個函式作為引數(與threading.Thread初始化程式相同),但您正在傳遞一個函式呼叫(最后的括號())。
所以,你有你傳遞的函式的順序運行,當第一個引發例外時,整個程式停止。
以下面一行為例:
schedule.every().day.at('06:30').do(run_threaded, lambda: functionA())
在[ReadTheDocs.Schedule]: Parallel execution (這可能是靈感的來源之一)中沒有呼叫 (target) 函式,所以上面的行應該是:
schedule.every().day.at('06:30').do(run_threaded, lambda: functionA) # functionA isn't called (no parentheses at the end) but it's rather passed as an argument不確定lambda的目的是什么,如果沒有它,事情看起來會簡單得多:
schedule.every().day.at('06:30').do(run_threaded, functionA)
將上述步驟應用于所有呼叫,我認為你會沒事的(運行引發例外的函式不會影響那些不引發例外的函式 - 至少那是threading中的行為),盡管有以下情況(在計劃檔案URL):
何時不使用時間表
...
- 并發執行(多執行緒)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486654.html
標籤:Python 多线程 python-多线程
