检查是否在芹菜任务

时间:2015-12-16 13:23:09

标签: python flask celery celery-task

如何检查celery执行的函数?

def notification():
   # in_celery() returns True if called from celery_test(), 
   #                     False if called from not_celery_test()
   if in_celery():
      # Send mail directly without creation of additional celery subtask
      ...
   else:
      # Send mail with creation of celery task
      ...

@celery.task()
def celery_test():
    notification()

def not_celery_test():
    notification()

1 个答案:

答案 0 :(得分:7)

以下是使用celery.current_task执行此操作的一种方法。以下是任务使用的代码:

def notification():
    from celery import current_task
    if not current_task:
        print "directly called"
    elif current_task.request.id is None:
        print "called synchronously"
    else:
        print "dispatched"

@app.task
def notify():
    notification()

这是您可以运行以执行上述操作的代码:

        from core.tasks import notify, notification
        print "DIRECT"
        notification()
        print "NOT DISPATCHED"
        notify()
        print "DISPATCHED"
        notify.delay().get()

我在第一个代码段中的任务代码位于名为core.tasks的模块中。我将代码推送到自定义Django管理命令的最后一段代码中。这测试了3个案例:

  • 直接致电notification

  • 通过同步执行的任务调用notification。也就是说,这项任务不会通过Celery发送给工人。任务代码在调用notify的相同过程中执行。

  • 通过工作人员运行的任务调用notification。任务代码在与启动它的进程不同的进程中执行。

输出结果为:

NOT DISPATCHED
called synchronously
DISPATCHED
DIRECT
directly called

print之后输出中的任务DISPATCHED中没有行,因为该行最终出现在工作日志中:

[2015-12-17 07:23:57,527: WARNING/Worker-4] dispatched

重要提示:我最初在第一次测试中使用if current_task is None,但它无效。我检查并重新检查。以某种方式,Celery将current_task设置为一个类似于None的对象(如果您在其上使用repr,则会获得None)但不是None。不确定那里发生了什么。使用if not current_task有效。

另外,我在Django应用程序中测试了上面的代码,但我没有在生产中使用它。可能有些我不知道的问题。

相关问题