1,后台执行第二个方法
2,说明
使用python的@run_on_executor 创建线程池,然后异步执行返回一个随机数字。
必须定义一个executor的属性,然后run_on_executor 注解才管用。
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
这个数字假设就是 tid,然后讲计算结果放到 map里面存储。
如果map 里面有 tid 的数据,则说明已经执行完毕。
同时前段使用 setInterval 定时执行check 方法。
然后检查成功之后 使用clearInterval 关闭循环。
代码如下:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, asynchronous, RequestHandler
from tornado import gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
# `pip install futures` for python2
# https://gist.github.com/methane/2185380 参考
html_content = """
任务测试
开始 """class MainPage(RequestHandler):
def get(self):
self.write(html_content)
MAX_WORKERS = 4
_result = {}
class AddJobHandler(RequestHandler):
# 必须定义一个executor的属性,然后run_on_executor 注解才管用。
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
@run_on_executor # 标记成后台程序执行。
def background_task(self, tid):
time.sleep(10) # 传递参数 10 秒。
_result[tid] = {"finish"}
@gen.coroutine
def get(self):
tid = str(int(time.time() * 10000))
self.background_task(tid)
self.write(tid)
class JobCheckHandler(RequestHandler):
def get(self):
tid = self.get_argument("tid")
if tid in _result.keys():
out = _result[tid] # 结果
del _result[tid] # 删除tid的数据。
self.write(str(out))
else:
self.write("")
# main 启动。
if __name__ == "__main__":
HTTPServer(Application([
("/", MainPage),
("/add_job", AddJobHandler),
("/job_check", JobCheckHandler)
], debug=True)).listen(9999)
print("start web .")
IOLoop.instance().start()
3,演示效果
4,总结
python 写几个代码还是非常的方便的,开发效率超级的高呢。
使用python 执行一个后台的代码也是非常的快的。