1,后台执行
本文的原文连接是: http://blog.csdn.net/freewebsys/article/details/78607822
未经博主允许不得转载。
博主地址是:http://blog.csdn.net/freewebsys
2,说明
使用python的ThreadPool 创建线程池,然后异步执行返回一个随机数字。
这个数字假设就是 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 multiprocessing.pool import ThreadPool
from multiprocessing.pool import ApplyResult
from tornado import gen
# https://gist.github.com/methane/2185380 参考
html_content = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<h1>任务测试</h1></br>
<button id="job">开始</button>
</body>
</html>
<script type="text/javascript">
function job_check(timer,tid) {
$.ajax({
type: "GET",
url: "job_check?tid="+tid,
success: function(msg){
console.log(msg);
if(msg != ""){
alert( "任务结果: " + msg );
clearInterval(timer);//结束轮询
}
}
});
}
jQuery(function($) {
$("#job").click( function () {
$.ajax({
type: "GET",
url: "add_job",
success: function(tid){
alert( "开始任务: " + tid );
timer = setInterval(function(){
console.log("run.");
job_check(timer,tid);
},1000);
}
});
});
})
</script>
"""
class MainPage(RequestHandler):
def get(self):
self.write(html_content)
_workers = ThreadPool(10)
_result = {}
# 后台任务。
def blocking_task(n, tid):
time.sleep(n)
print(tid)
_result[tid] = {"finish"}
class AddJobHandler(RequestHandler):
@gen.coroutine
def get(self):
tid = str(int(time.time() * 10000))
_workers.apply_async(blocking_task, (10, tid)) # 传递参数 10 秒。
self.write(tid)
self.finish() # 先finish 掉,然后在后台执行。
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,演示效果
前端的js 使用的是百度的cdn。速度还可以呢。
http://cdn.code.baidu.com/
4,总结
python 写几个代码还是非常的方便的,开发效率超级的高呢。
使用python 执行一个后台的代码也是非常的快的。
默认下,tornado 支持一些异步执行。也可以研究下使用。
http://tornado.readthedocs.io/en/stable/gen.html
本文的原文连接是: http://blog.csdn.net/freewebsys/article/details/78607822
未经博主允许不得转载。
博主地址是:http://blog.csdn.net/freewebsys
本文介绍了一个使用Python和Tornado实现的异步任务处理示例。通过创建线程池来执行后台任务,并利用前端定时轮询的方式检查任务状态。
256

被折叠的 条评论
为什么被折叠?



