我有一个异步协程,我想使用计时器/线程终止。协程基于来自 aiortc的这个示例。
args = parse_args()
client = Client(connection, media, args.role)
# run event loop
loop = asyncio.get_event_loop()
try:
timer = None
if args.timeout:
print("Timer started")
timer = threading.Timer(args.timeout, loop.run_until_complete, args=(client.close(),))
timer.start()
loop.run_until_complete(client.run())
if timer:
timer.join()
except KeyboardInterrupt:
pass
finally:
# cleanup
loop.run_until_complete(client.close())
这不起作用并引发RuntimeError('This event loop is already running')
为什么这会引发错误?我的猜测是这是因为循环在不同的线程上运行。但是,创建一个新循环不起作用,因为它会将未来附加到另一个循环。
def timer_callback():
new_loop = asyncio.new_event_loop()
new_loop.run_until_complete(client.close())
之后,如何使用计时器来结束脚本?