Django 中的芹菜超时

Celery timeout in Django

不同时期celery中一共有8个任务运行。它们都是事件驱动的任务。在某个事件之后,他们被解雇了。并且特定任务会持续进行,直到满足某些条件为止。

我已经注册了一个检查特定条件的任务将近两分钟。此任务大部分时间都运行良好。但有时任务的预期行为并没有达到。

任务签名如下:

tasks.py

import time
from celery import shared_task

@shared_task()
def some_celery_task(a, b):
    main_time_end = time.time() + 120
    while time.time() < main_time_end:
        ...
        # some db operations here with given function arguments 'a' and 'b' 
        # this part of the task get execute most of the time

    if time.time() > main_time_end:
        ...
        # some db operations here.
        # this part is the part of the task that doesn't get executed sometimes

views.py

# the other part of the view not mentioned here
# only the task invoked part 
some_celery_task.apply_async(args=(5, 9), countdown=0)

我对 celery 任务超时场景感到困惑。这是否意味着任务将从超时处停止或自动重试? 如果你们对超时和重试有任何清晰的认识,那将是一个很大的帮助。
上面解释的场景背后的原因可能是什么?对此问题的任何帮助将不胜感激。谢谢。

检查 Celery documentation on Tasks - 基础知识记录得很好。


如果任务失败或被终止 - 任务将具有 states.FAILURE 状态。除非特别编码,否则不会重试。如果日志记录配置正确 - 您可能会在超时或其他代码异常的情况下在日志中看到异常消息。


当超出 Celery 任务 TIME_LIMIT - 任务立即终止:

The worker processing the task will be killed and replaced with a new one.

此外,TimeLimitExceeded 异常将引发 Task handler raised error: "TimeLimitExceeded(2700)"

之类的消息

如果设置了 Celery SOFT_TIME_LIMIT 并且小于 TIME_LIMIT 并且超出了 - 那么 SoftTimeLimitExceeded 将引发异常,允许它在任务中被捕获并执行清理动作。


worker 从代理队列中消费消息(任务)时 - 代理需要知道消息已成功消费。确认消息工作者 acknowledges (ACK) 成功消费到代理 。在消息未被确认之前,它不会从代理中删除,但也不可用于消费 ("invisible")。未确认 - 消息将重新传送回代理队列,再次可供使用。

重新传递未确认的消息逻辑取决于代理:

  • AMQP (RabbitMQ) 代理 - 跟踪与 worker 的连接状态,如果连接丢失 - returns 消息返回队列。

  • Redis 或 SQS broker 有自己的 timeout 之后,如果没有确认,消息将被重新传递到 broker 队列。


默认情况下,celery worker 在任务开始时立即确认消息。

如果设置了 ACKS_LATE - worker 只有在成功执行任务后才会向 broker 确认。


可以 RETRY task, by catching exception in the task and sending same task back to the broker for re-execution - then this same task with same id will be queued at broker. Countdown 选项允许指定重试任务之前的延迟。


可以设置Celery任务执行和其他选项globally in settings.py or per task as arguments


推荐的设计任务/逻辑的方式,考虑到这些事件是完全合法的,并看到它们正常(但实际上并不期望)在某个时候发生并做好准备:

  • 任务可能会失败(下一个相同的任务可能对两者都有效,或者检查特定的工作是否未完成并重新启动任务
  • 同样的任务可能会再次运行(幂等性
  • 相似的任务可以运行同时进行(锁定