Setup:
So I have a clients array consisting of client objects. Also two async functions, one them is processing the incoming messages from a WebSocket and the other one is executing some API calls with the given client object.
When a certain message arrives from the WebSocket connection, function_a should detect it and start a for loop in the clients array. For each client object in the clients array I want to trigger function_b. But the function_b should run concurrent for the each client.
Example Code:
clients = {}
async def function_a(ws_message): # this is being called each time when a new message arrives
if ws_message == 'signal_message':
for client in clients:
await function_b(client)
async def function_b(client):
# get client parameters
# make an API request with those parameters
UPDATE || Code with asyncio.gather()
So I have updated my actual code with asyncio.gather() but there is still ~500 ms delay between each function task. I am not sure but I guess this is because my function_b has some non-async blocking code thanks to requests library.
clients = {}
tasks = []
async def function_a(ws_message):
if ws_message == 'signal_message':
for client in clients:
task = asyncio.ensure_future(function_b(client))
tasks.append(task)
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
async def function_b(client):
# get client parameters
# make an API request with those parameters
As I said this doesn't work either.
Issue:
Right now the function_b gets triggered without any issue, however function_b runs about 500ms and the await calls from the function_a waits for the one before it to finish. So for example the function_b process for the second client object in the clients array takes ~1000ms to finish after the WebSocket message has received. And this delay gets bigger with the each call obviously.
Solution?
Have can fix this so the each function_b process can run concurrently? Thanks in advance.
awaitpauses in its code? If it is synchronous, asyncio can't run it in parallel.asyncio.sleep()ortime.sleep()in it. Only thing that is synchronous it has are the API calls which are handled by request module. Right now I'm converting to aiohttp instead of request to see if it makes any difference at all.