关闭异步IO循环

bd1hkmkf  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(303)
  1. import asyncio
  2. import aiohttp
  3. aut_token = ("token")
  4. tasks = []
  5. iter_flag = True
  6. interval = 0
  7. seq = 0
  8. class WAPI:
  9. async def receiver(WAPI_S):
  10. async for msg in WAPI_S:
  11. global interval
  12. global seq
  13. data = msg.json()
  14. seq = data.get("s")
  15. if data.get("op") == 10:
  16. interval = data.get("d").get("heartbeat_interval") / 1000
  17. if data.get("op") == 11:
  18. pass
  19. raise aiohttp.ClientError
  20. async def heartbeating(WAPI_S):
  21. while iter_flag:
  22. await WAPI_S.send_json({
  23. "op": 1,
  24. "d": seq
  25. })
  26. await asyncio.sleep(interval)
  27. async def event_manager():
  28. loop = asyncio.get_running_loop()
  29. try:
  30. async with aiohttp.ClientSession() as session:
  31. async with session.ws_connect("url") as WAPI_S:
  32. task_receive = loop.create_task(WAPI.receiver(WAPI_S)); task_heartbeating = loop.create_task(WAPI.heartbeating(WAPI_S))
  33. tasks.append(task_receive); tasks.append(task_heartbeating)
  34. await asyncio.gather(*tasks)
  35. except aiohttp.ClientError:
  36. global iter_flag
  37. iter_flag = False
  38. await asyncio.sleep(interval)
  39. for task in tasks:
  40. task.cancel()
  41. try:
  42. loop.close()
  43. except:
  44. loop.stop()
  45. asyncio.run(WAPI.event_manager())

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

暂无答案!

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

相关问题