Search code examples
pythonwebsocketasync-awaittornadoevent-loop

How to stop a task generated by Tornado spawn_task


I am writing a WebSocket server using Python's Tornado framework.

class MyHandler(WebSocketHandler):

    def open(self, device: str):
        async def aTask():
            while True:
                # do something again and again until the connection closes
        IOLoop.current().spawn_task(aTask)

    def on_close(self):
        # want to stop/destroy aTask

    def on_message(self, message):
        print(message)

How can I stop and destroy the background task generated on connection open?


Solution

  • Set an attribute on the current instance which you can check in the while loop. Set the attribute to False when connection closes:

    def open(self, device):
        setattr(self, 'is_open', True)
    
        while self.is_open:
            # ...
    
    def on_close(self):
        setattr(self, 'is_open', False)