我的设置是 python tornado 服务器,它使用ThreadPoolExecutor
. 在某些情况下,任务可能会变成无限循环。使用with_timeout
装饰器,我设法捕获了超时异常并将错误结果返回给客户端。问题是任务仍在后台运行。如何阻止任务在 中运行ThreadPoolExecutor
?或者可以取消Future
吗?这是重现问题的代码。使用 tornado 4 和 concurrent.futures 库运行代码并转到http://localhost:8888/test
from tornado.concurrent import run_on_executor
from tornado.gen import with_timeout
from tornado.ioloop import IOLoop
import tornado.web
from tornado import gen
from concurrent.futures import ThreadPoolExecutor
import datetime
MAX_WAIT_SECONDS = 10
class MainHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(2)
@run_on_executor
def test_func(self):
...
#infinite loop might be here
...
@tornado.gen.coroutine
def get(self):
future = self.test_func()
try:
result_search_struct = yield with_timeout(datetime.timedelta(seconds=MAX_WAIT_SECONDS), future )
self.write({'status' : 0})
self.finish()
except Exception, e:
#how to cancel the task here if it was timeout
future.cancel() # <-- Does not work
self.write({'status' : 100})
self.finish()
application = tornado.web.Application([
(r"/test", MainHandler),
])
application.listen(8888)
IOLoop.instance().start()