我正试图找到一种方法,在我的websocketdef on_message()
函数的两个内部函数之间委派我的计算机处理能力。此外,我的代码似乎跳过了def on_message()
,我不太确定是否需要在args中声明这些内部函数?
提前谢谢。
import websocket
import concurrent.futures as mp
Stock_stream = 'wss://data.alpaca.markets/stream'
def on_open(ws):
print("opened")
def on_message(ws, message):
def job():
print("do job")
with mp.ProcessPoolExecutor(max_workers=3) as pool:
results = pool.map(job)
return results
def trade():
print("trade")
with mp.ProcessPoolExecutor(max_workers=1) as pool:
results = pool.map(trade)
return results
def on_close(ws):
print("bye")
ws = websocket.WebSocketApp(Stock_stream, on_open=on_open, on_message=on_message, on_close=on_close)
ws.run_forever()
谢谢
正如我所知,websocket客户端是一个同步库。因此,当您需要在响应之前进行长时间的处理时,请使用多线程。在您的情况下,在线程job()
或trade()
中运行并将ws
传递给它们。
...
def on_message(ws, message):
def job(ws):
print("do job")
with mp.ProcessPoolExecutor(max_workers=3) as pool:
results = pool.map(job)
# send result to ws
threading.Thread(target=job, args=(ws,), daemon=True).start()
...