Close a task in Python based on condition

后端 未结 2 1648
半阙折子戏
半阙折子戏 2021-01-27 11:30

I\'m using AsyncIO and the Websockets module to create two concurrent tasks in Python, each one connects to a websocket server and receives messages.

I\'m trying to creat

2条回答
  •  广开言路
    2021-01-27 12:03

    You can use asyncio.wait_for:

    async def connect(URI):
        async with websockets.client.connect(URI) as ws:
            while True:
                try:
                    msg = await asyncio.wait_for(ws.recv(), 4)
                except asyncio.TimeoutError:
                    break
                # do something with msg
    
            print('Not receiving updates anymore')
    

提交回复
热议问题