使用线程的方式实现异步执行任务
# -*- coding: utf-8 -*-
from flask import Flask, jsonify
from time import sleep
from concurrent.futures import ThreadPoolExecutor
# 创建线程池执行器
executor = ThreadPoolExecutor(2)
app = Flask(__name__)
# 耗时任务是否完成(推荐redis存储 唯一标识)
gl = True
@app.route('/')
def run_jobs():
# 判断是否需要执行耗时任务
global gl
if gl:
print "submit"
executor.submit(long_task, 'hello', 123)
else:
gl = True
return 'long task complete.'
return 'long task running.'
# 耗时任务
def long_task(arg1, arg2):
print "args: %s %s!" % (arg1, arg2)
sleep(20)
print "Task is done!"
global gl
gl = False
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)