Skip to content

Instantly share code, notes, and snippets.

@marksilvis
Last active October 23, 2017 21:07
Show Gist options
  • Save marksilvis/f240ceeda244f047f8f0934c4c42e69f to your computer and use it in GitHub Desktop.
Save marksilvis/f240ceeda244f047f8f0934c4c42e69f to your computer and use it in GitHub Desktop.
Tornado server with multiple periodic callbacks and a repeated background task
# python
import logging
import time
from tornado import gen, httpserver, ioloop, log, web
log.enable_pretty_logging()
class MainHandler(web.RequestHandler):
@gen.coroutine
def get(self):
ioloop.IOLoop.instance().spawn_callback(callback)
self.write("DONE\n")
@gen.coroutine
def callback():
print("\nCalback has completed\n")
@gen.coroutine
def small_loop():
while True:
yield print('\nin small loop!\n')
yield gen.sleep(10)
def make_app():
return web.Application([
(r"/", MainHandler)
],
debug=False)
def main():
"""Make application"""
app = make_app()
# start server
server = httpserver.HTTPServer(app)
server.listen(8080)
# server.start()
# app.listen(8080)
ioloop.IOLoop.instance().spawn_callback(small_loop)
io_loop = ioloop.IOLoop.instance()
# background update every x seconds
task = ioloop.PeriodicCallback(
lambda: print('period'),
2000)
task.start()
print('starting ioloop')
io_loop.start()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment