Close a task in Python based on condition

后端 未结 2 1642
半阙折子戏
半阙折子戏 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 11:52

    There are a couple ways to do this.

    1. You can set a timeout in the package you are using within the async routine.
    2. You can use asyncio and terminate tasks when they reach a timeout.
    3. You can use non-blocking sockets for all operations, and not use asyncio at all, but use select() or poll(). This is very efficient but a lot more complex.

    I would go in this order, the first one being the easiest and most preferred in most cases. Websockets seem to handle timeouts: https://github.com/websocket-client/websocket-client/blob/29c15714ac9f5272e1adefc9c99b83420b409f63/websocket/_socket.py#L99

    You probably want to set a timeout on the socket. Generally this is done with https://docs.python.org/3.8/library/socket.html#socket.socket.settimeout

    I suppose websockets expose this functionality somewhere though, but I am not familiar with it.

    0 讨论(0)
  • 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')
    
    0 讨论(0)
提交回复
热议问题