Skip to content

Instantly share code, notes, and snippets.

@stevepeak
Last active February 16, 2022 07:15
Show Gist options
  • Save stevepeak/4520732 to your computer and use it in GitHub Desktop.
Save stevepeak/4520732 to your computer and use it in GitHub Desktop.
Tornado Long-Polling Example
import tornado.ioloop
import tornado.web
import time
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self, request):
if request is None:
self.application.go = False
self.write("Waiting for GET @ http://localhost:8888/go...<br>")
self.flush()
self._do_wait()
else:
self.application.go = True
self.finish('Thanks!')
def _do_wait(self, timeout_trys=10):
if self.application.go:
self.write('Finish')
self.finish()
else:
self.write("Sleeping 2 second, timeout_trys=%s<br>" % timeout_trys)
self.flush()
tornado.ioloop.IOLoop.instance().add_timeout(time.time() + 2,
lambda: self._do_wait(timeout_trys-1))
application = tornado.web.Application([
(r"/(\w+)?", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
@stevepeak
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment