我目前在芹菜中使用Task.delay()
(与RabbitMQ一起使用)执行异步任务。这些任务分配给8个工作人员,在这些任务中,我正在执行数据库插入操作。
有时任务将失败,并且不会发生数据库插入。这可能是由于超时或JSON解码错误所致。我想捕捉到执行失败。
以下是相关代码:
views.py
def celery_url_filtering(request):
for each_data in dataset:
#each_data is a Json object
res = result.delay(each_data)
while(res.status == 'PENDING'):
pass
return JsonResponse({'ok':'Success'})
tasks.py
@app.task
def result(dataeach_data):
# Parse each_data and do data insertion here
return "Something"
如何在列表中捕获失败的执行?
答案 0 :(得分:0)
据您所知,您希望了解“待处理”或“失败”任务,并重试/应用一些应用程序逻辑。
如果是这样,您可以根据需要以固定的时间表(每天/每小时)运行cron。此Cron作业可以根据您的计划捕获过去一天/小时内失败的任务。
您可以使用Django ORM使用django-celery-beat来设置cron作业,使用django-celery-results来存储celery任务结果。
例如,您可以执行一个芹菜任务
from celery import shared_task
from django_celery_results.models import TaskResult
**tasks.py**
@shared_task(name="failed_task_cron", bind=True)
def failed_task_cron(self, **kwargs):
"""
Celery task to run on daily schedule to do something with the failed tasks
"""
tasks = TaskResult.objects.filter(status='FAILURE')
# tasks is a queryset of all the failed tasks
# Perform application logic
您可以在芹菜设置中为上述任务设置cron
from celery.schedules import crontab
# ...
CELERY_BEAT_SCHEDULE = {
"failed_task_cron": {
"task": "path/to/tasks.failed_task_cron",
"schedule": crontab(hour=1) # Runs every hour
}
}