tornado equivalent of delay

后端 未结 3 1930
無奈伤痛
無奈伤痛 2020-12-29 07:24

Is there an equivalent command in tornado for delay function without affecting the main process to sleep (thus the callbacks would execute even when the main thread is dealy

相关标签:
3条回答
  • 2020-12-29 07:55

    May be redundant

    I like callback style

    class MyHandler(RequestHandler):
        @asynchronous
        def get(self):
            self.write("sleeping .... ")
            self.flush()
            IOLoop.instance().add_timeout(time.time() + 5, self._process)
    
        def _process(self)
            # Do nothing for 5 secs
            self.write("I'm awake!")
            self.finish()
    
    0 讨论(0)
  • 2020-12-29 08:02

    Try this:

    import time
    from tornado.ioloop import IOLoop
    from tornado.web import RequestHandler, asynchronous
    from tornado import gen
    
    class MyHandler(RequestHandler):
        @asynchronous
        @gen.engine
        def get(self):
            self.write("sleeping .... ")
            self.flush()
            # Do nothing for 5 sec
            yield gen.Task(IOLoop.instance().add_timeout, time.time() + 5)
            self.write("I'm awake!")
            self.finish()
    

    Taken from here.

    0 讨论(0)
  • 2020-12-29 08:08

    Note that since 4.1 they've added a gen.sleep(delay) method.

    so

    yield gen.Task(IOLoop.instance().add_timeout, time.time() + 5)
    

    would just become

    yield gen.sleep(5)
    
    0 讨论(0)
提交回复
热议问题