使用 django-celery-3.0.17、celery-3.0.21 和 django-1.5.1,我正在尝试监控链执行。我找到了一个解决方案,但对我来说似乎有点奇怪,所以如果可能的话,我正在寻找一个更简单的解决方案。这是我的代码:
视图.py
def runCod(request):
runFunTask = runFunctions.delay(shpId, codId, stepValues, bboxTuple);
getRunFunStatus.delay(runFunTask)
return render_to_response('tss/append_runCod.html',
{'runFunTask': runFunTask},
context_instance=RequestContext(request))
def getProgressCod(request):
task = AsyncResult(taskId)
currStep = task.result['step']
totSteps = task.result['total']
if task.status == 'SUCCESS':
task.revoke() # Manually terminate the runFunctions task
response = dumps({'status':task.status,'currStep':currStep,'totSteps':totSteps})
return HttpResponse(response, mimetype='application/json')
任务.py
@task()
def runFunctions(shpId, codId, stepValues, bboxTuple):
# ... Code to define which functions to launch ...
stepsToLaunch = [fun1, fun2, fun3, fun4, fun5]
chainId = chain(stepsToLaunch).apply_async()
chainAsyncObjects = [node for node in reversed(list(nodes(chainId)))]
current_task.update_state(state="PROGRESS", meta={'step':1, 'total':numSteps})
for t in range(10800): # The same max duration of a celery task
for i, step in enumerate(chainAsyncObjects):
currStep = i+1
if step.state == 'PENDING':
current_task.update_state(state="PROGRESS", meta={'step':currStep, 'total':numSteps})
break
if step.state == 'SUCCESS':
if currStep == numSteps:
current_task.update_state(state="SUCCESS", meta={'step':currStep, 'total':numSteps})
# This task will be terminated (revoked) by getProgressCod()
if step.state == 'FAILURE':
return
sleep(1)
鳕鱼.js
function getProgressCod(taskId){
var aoiStatus, allStatus, currStep, totSteps;
var interval = 2000; // Perform ajax call every tot milliseconds
var refreshId = setInterval(function(){
$.ajax({
type: 'get',
url: 'getProgressCod/',
data:{'taskId': taskId,},
success: function(response){},
});
}, interval);
}
这就是正在发生的事情:
runCod()
启动异步任务runFunctions()
;runFunctions()
创建并启动一系列子任务- 在
runFunctions()
最后的循环中,我每秒都会更新它自己的“进度”状态,查看单链子任务状态。(参考1和2) - 要知道发生了什么,用户会收到 javascript 函数的通知,该函数每 2 秒发出一次对python 函数
getProgressCod()
的 ajax 请求getProcessCod()
getProcessCod()
python 函数查看runFunctions()
状态,当它是“成功”时,它会撤销(终止)runFunctions()
执行。
我没有找到另一种方法,因为如果我runFunctions()
在链的每个子任务在其最终循环内完成时返回,我无法将其“成功”状态通知给用户,因为getProcessCod()
将获得一个None
执行的对象task.status