Asynchronous execution of a function called several times in a loop

30 views Asked by At

There's a problem. Wrote an asynchronous function. With different data in the arguments, I call this function, walking through the list of arguments for it. I don’t know how to make these functions run asynchronously rather than sequentially

import asyncio
import aiohttp
import aiomoex
import time

tks = ['YNDX', 'TATN', 'GAZP']
async def main(tk):
    async with aiohttp.ClientSession() as session:
        data = await aiomoex.get_board_candles(session=session, security=tk, interval=1, start='2023-08-01')
        print(data)
    return data

for tk in tks:
    asyncio.run(main(tk))
1

There are 1 answers

2
Andrej Kesely On

IIUC, you want to get the data in parallel for various tickers.

Here is example how you can structure your code (I replaced aiomoex.get_board_candles() with mockup function, in your code use your function):

import asyncio

import aiohttp

# import aiomoex

tks = ["YNDX", "TATN", "GAZP"]


#
async def mockup_function(session, param):
    await asyncio.sleep(3)
    return param, 123


async def main(tks):
    async with aiohttp.ClientSession() as session:
        # data = await aiomoex.get_board_candles(
        #     session=session, security=tk, interval=1, start="2023-08-01"
        # )
        tasks = {asyncio.create_task(mockup_function(session, tk)) for tk in tks}
        data = await asyncio.gather(*tasks)

    print(data)


asyncio.run(main(tks))