【问题标题】:Capture failed tasks from Celery workers during task execution在任务执行期间从 Celery worker 中捕获失败的任务
【发布时间】:2020-05-05 01:38:09
【问题描述】:

我目前在 celery(与 RabbitMQ)中使用Task.delay() 来执行异步任务。任务分配给 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"

如何在列表中捕获失败的执行?

【问题讨论】:

  • 为什么不在任务中处理这些错误?
  • @DejanLekic,错误是随机的,所以无法追查根本原因

标签: python-3.x asynchronous rabbitmq celery django-celery


【解决方案1】:

据我所知,您的担忧是您想查看“PENDING”或“FAILURE”任务并重试/应用一些应用程序逻辑。

如果是这样,您可以根据需要让 cron 以固定的时间表、每天/每小时等方式运行。此 cron 作业可以根据您的计划捕获在最后一天/小时内失败的任务。

您可以使用django-celery-beat 设置 cron 作业,使用django-celery-results 使用 Django ORM 存储 celery 任务结果。

例如,你可以有一个像这样的 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

您可以在 celery 设置中像这样为上述任务设置 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
    }
}

【讨论】:

  • 正如我在上面的问题中提到的,如果我在每个任务中的数据插入由于 JsonDecode 错误而失败,Celery 是否将其归类为 FAILED 任务????
  • 任何导致 celery 任务无法完成的事情都会导致 FAILURE 状态。您可以尝试使用 shell 进行检查。
  • 现在,假设我不想实现 crontab,所以,我将在 JsonResponse() 之前继续打印这一行“TaskResult.objects.filter(status='FAILURE')”问题中显示的views.py中的函数......它会打印失败的任务吗?
  • 会的。所有任务的查询集都失败了。但随着时间的推移,这可能是一个需要管理的庞大集合!如果你正在为这些任务做一些处理,最好在一段时间内继续摆脱它们。因此,出现了 cron 作业。
猜你喜欢
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 2021-01-24
  • 2014-12-24
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
  • 2017-06-15
相关资源
最近更新 更多