Close a task in Python based on condition

后端 未结 2 1679
半阙折子戏
半阙折子戏 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.

提交回复
热议问题