I'd like to process coroutines in batches like:
import asyncio
async def test(i):
print(f"Start Task {i}")
await asyncio.sleep(0.1)
print(f"Finished Task {i}")
async def main():
for i in range(10):
await asyncio.gather(*[test(10*i+j) for j in range(10)])
asyncio.run(main())
Is there a way to do this with Python builtins or libraries so that I do not have to create the batches individually?
Unfortunately
async with asyncio.Semaphore(10):
await asyncio.gather(*[test(i) for i in range(100)])
isn't processing the coroutines as expected: the coroutines are created all at once. Only the excecutions are limited. I don't want to create all tasks at once. The tasks should be created in batches.
gather
returns results in the same order that it was passed to the function, so you'll see task 1 first, task 2 second etc. Tasks are actually processed in async batches 10 times, try changing to wait and you'll see that results gets randomised since wait does not preserve the result order. – Domiciliategather
is to run the coroutines concurrently... Hence the behaviour you observe is correct... I don't see the problem of using afor
loop to create your batches.... Otherwise try reading about the threads: docs.python.org/3/library/asyncio-task.html#id10 – Unbend