-
-
Save ninehills/4465999 to your computer and use it in GitHub Desktop.
tornado add block task to ThreadPool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import sleep | |
import tornado | |
from multiprocessing.pool import ThreadPool | |
_workers = ThreadPool(10) | |
class BackgroundMix(tornado.web.RequestHandler): | |
"""将block任务放入线程池中执行 | |
EXAMPLE: | |
# blocking task like querying to MySQL | |
def blocking_task(n): | |
sleep(n) | |
return n | |
class Handler(RequestHandler, BackgroundMix): | |
@asynchronous | |
def get(self): | |
self.run_background(blocking_task, self.on_complete, (10,)) | |
def on_complete(self, res): | |
self.write("Test {0}<br/>".format(res)) | |
self.finish() | |
""" | |
def run_background(self, func, callback, args=(), kwds={}): | |
self.ioloop = tornado.ioloop.IOLoop.instance() | |
def _callback(result): | |
self.ioloop.add_callback(lambda: callback(result)) | |
_workers.apply_async(func, args, kwds, _callback) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这个有两个地方不好用
无法处理任务抛出的异常
原来的任务比如是blocking_task(10),这里run_background的最后一个参数却不一样,具体是这样的