Skip to content

Instantly share code, notes, and snippets.

@illume
Last active Jun 11, 2019
Embed
What would you like to do?
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