python tornado 异步与延迟任务
ThreadPoolExecutor模块和run_on_exexutor装饰器。就是建立线程池,用run_on_executor装饰的函数即运行在其中线程中,从而主线程中分离出来,达到异步的目的。
tornado的IOLoop.add_callback,执行后就会执行下一行代码,而callback函数将在下一轮事件循环中才调用,从而就能实现延迟任务。
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
import tornado.gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import time
from tornado.options import define, options
define("port", default=8888, help="run in the given port", type=int)
class SleepHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(2)
def get(self):
tornado.ioloop.IOLoop.instance().add_callback(self.sleep)
self.write("when i sleep")
@run_on_executor
def sleep(self):
time.sleep(5)
print("yes")
return 5
if __name__ == '__main__':
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[
(r'/sleep/', SleepHandler), ])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()