Skip to content

Instantly share code, notes, and snippets.

@illume
Last active June 11, 2019 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save illume/6919e21df88fea669043a77842e46ab8 to your computer and use it in GitHub Desktop.
Save illume/6919e21df88fea669043a77842e46ab8 to your computer and use it in GitHub Desktop.
Tornado run task in a thread pool.
""" Run a task in a background thread.
python3 -m pip install tornado --user
python3 tornado_thread.py
curl http://localhost:8888/2
See `run_on_executor` documentation:
https://www.tornadoweb.org/en/stable/concurrent.html#tornado.concurrent.run_on_executor
See for another approach:
- https://www.tornadoweb.org/en/stable/faq.html#why-isn-t-this-example-with-time-sleep-running-in-parallel
```python
class ThreadPoolHandler(RequestHandler):
async def get(self):
for i in range(5):
print(i)
await IOLoop.current().run_in_executor(None, time.sleep, 1)
```
"""
import tornado.ioloop
import tornado.web
from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor
class MainHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(max_workers=4)
@run_on_executor
def background_task(self, num):
import time
time.sleep(int(num))
return num
@tornado.gen.coroutine
def get(self, num):
res = yield self.background_task(num)
self.write(res)
def make_app():
return tornado.web.Application([(r"/(.*)", MainHandler)])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment