Search code examples
pythonloopstimertornadopolling

How to return some variable once in few seconds to client?


I'm learning python+tornado currently and was stopped with this problem: i need to write some data one every few sec (for example) to client even using self.write(var)
I've tried:

  1. time.sleep - it's blocked
  2. yield gen.Task(IOLoop.instance().add_timeout, time.time() + ...) - great thing but I still got full request at the end of timeout
  3. .flush - in some reason it don t want to return Bdata to client
  4. .PeriodicCallback - browsers window just loading and loading like with another upper methods

I imagine my code like

class MaHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        for x in xrange(10):
            self.write(x)
            time.sleep(5) #yes,it's no working

That's all. Thanks for any help with this. I'm solving this like 4-5 days and really can't make it by myself.

I still think it can't be done only with server side. It coud be closed.


Solution

  • Use the PeriodicCallback class.

    class MyHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        def get(self):
            self._pcb = tornado.ioloop.PeriodicCallback(self._cb, 1000)
            self._pcb.start()
    
        def _cb(self):
            self.write('Kapooya, Kapooya!')
            self.flush()
    
        def on_connection_close(self):
            self._pcb.stop()