【发布时间】:2020-08-22 07:25:52
【问题描述】:
如何重新启动异步循环?我正在用 asyncio 收听 websocket。我想停止听,重新开始整个循环。我怎样才能做到这一点?我在下面的尝试不起作用
async def start_websocket(streams):
print("using streams {}".format(streams))
await asyncio.sleep(30)
def _start_loop(loop, ws):
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(ws)
except CancelledError:
pass
for streams in ["a", "b"]:
ws = start_websocket(streams) # coroutine
loop = asyncio.get_event_loop()
# in case of already running, cancel websocket
if loop.is_running():
[t.cancel() for t in asyncio.Task.all_tasks()]
# restart websocket
Thread(target=_start_loop, args=(loop, ws)).start()
time.sleep(2)
我来了
RuntimeError: This event loop is already running
【问题讨论】:
标签: python asynchronous python-asyncio