关闭异步IO循环

bd1hkmkf  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(241)
import asyncio
import aiohttp
aut_token = ("token")
tasks = []
iter_flag = True
interval = 0
seq = 0
class WAPI:

    async def receiver(WAPI_S):
        async for msg in WAPI_S:
            global interval
            global seq
            data = msg.json()
            seq = data.get("s")
            if data.get("op") == 10:
                interval = data.get("d").get("heartbeat_interval") / 1000 
            if data.get("op") == 11:
                pass
            raise aiohttp.ClientError

    async def heartbeating(WAPI_S):
        while iter_flag:
            await WAPI_S.send_json({
                            "op": 1,
                            "d": seq
                        })

            await asyncio.sleep(interval)

    async def event_manager():
        loop = asyncio.get_running_loop()
        try:
            async with aiohttp.ClientSession() as session:
                async with session.ws_connect("url") as WAPI_S: 
                    task_receive = loop.create_task(WAPI.receiver(WAPI_S)); task_heartbeating = loop.create_task(WAPI.heartbeating(WAPI_S))
                    tasks.append(task_receive); tasks.append(task_heartbeating)
                    await asyncio.gather(*tasks)
        except aiohttp.ClientError:
            global iter_flag
            iter_flag = False
            await asyncio.sleep(interval)
            for task in tasks:
                task.cancel()
            try:
                loop.close()
            except:
                loop.stop()

asyncio.run(WAPI.event_manager())

我试图通过循环关闭来实现捕获clienterror异常,但是,loop.close抛出“runtimeerror:事件循环在将来完成之前停止”
如何正确实施拦截?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题