pyList

Tornado 将阻塞任务用异步Handler委派给工作线程池

两个用 tornado.concurrent.run_on_executor 来实现把Handler 接到的任务分派到后台运行的例子

Tornado 将阻塞任务用异步Handler委派给工作线程池

import time

import tornado
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor   # `pip install futures` for python2

from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from tornado import gen

MAX_WORKERS = 4


class Handler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)

    @run_on_executor
    def background_task(self, i):
        """ This will be executed in `executor` pool. """
        time.sleep(10)
        return i

    @gen.coroutine
    def get(self, idx):
        """ Request that asynchronously calls background task. """
        res = yield self.background_task(idx)
        self.write(res)


HTTPServer(Application([("/(\d+)", Handler)],debug=True)).listen(8888)

IOLoop.instance().start()

第二个

import datetime
import time

from tornado.ioloop import IOLoop
import tornado.web
from tornado import concurrent

executor = concurrent.futures.ThreadPoolExecutor(8)


class Handler(tornado.web.RequestHandler):

    def get(self):
        def task(arg):
            for i in range(10):
                time.sleep(1)
                print(arg, i)

        executor.submit(task, datetime.datetime.now())
        self.write('request accepted')


def make_app():
    return tornado.web.Application([
        (r"/", Handler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(8000, '0.0.0.0')
    IOLoop.current().start()
本文标签: Tornado 后台任务 线程池
本文网址: https://pylist.com/t/1545826346 (转载注明出处)
如果你有任何建议或疑问可以在下面 留言
发表第一条评论!
验证码图片
相关推荐