Alfian AP
Alfian AP

Reputation: 3

Why asyncio loop cant stop?

I have a piece of code like this:

import asyncio
import aiohttp
from time import process_time

ts = process_time()

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

async def bot(s):
    async with s.get('https://httpbin.org/uuid') as r:
        resp = await r.json()
        print(resp['uuid'][0])

        if resp['uuid'][0] == '0':
            print("EUREEKA")
            return

async def main():
    async with aiohttp.ClientSession() as s:
        await asyncio.gather(*[bot(s) for _ in range(0, 1000)])

if __name__ == "__main__":
    asyncio.run(main())
    te = process_time()

    print(te-ts)

I want to stop the loop process when "EUREEKA" appears. I use return but it doesn't stop either. What is the correct way to stop it? result of code

Upvotes: 0

Views: 226

Answers (1)

user4815162342
user4815162342

Reputation: 154911

asyncio.gather will wait for all tasks to complete. If you want to stop on first task that reaches the finish line, you can use asyncio.wait with FIRST_COMPLETED:

async def main():
    async with aiohttp.ClientSession() as s:
        done, pending = await asyncio.wait(
            [bot(s) for _ in range(0, 1000)],
            return_when=asyncio.FIRST_COMPLETED
        )
        # ensure we notice if the task that is done has actually raised
        for t in done:
            await t
        # cancel the tasks that haven't finished, so they exit cleanly
        for t in pending:
            t.cancel()

Upvotes: 1

Related Questions