简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM