如何确保Celery任务的子任务与父任务进入同一队列?

时间:2015-10-20 18:58:59

标签: python celery

我有芹菜任务,可能会排队其他子任务。如果工作人员从高优先级队列中提取该任务,然后该任务将其他任务排队,我希望新任务返回进入高优先级队列。但是,如何以编程方式获取当前正在执行的任务来自的队列?

我知道我可以做一些事情,例如传递一个额外的参数,到原始的my_task.apply_async()调用,它指定一个用于子任务的队列,然后我可以通过方法/类的链传递它紧缩任务,但这看起来很混乱,很难维护。似乎只需要询问Celery就可以在某处获得队列信息。

1 个答案:

答案 0 :(得分:2)

我发现队列信息可以通过current_task.request.delivery_info['exchange']获得 所以,我最终使用的解决方案如下:

def get_source_queue(default=None):
    """
    Finds and returns the queue that the currently-executing task (if any) came from.
    """
    from celery import current_task
    if current_task is not None and 'exchange' in current_task.request.delivery_info:
        source_queue = current_task.request.delivery_info['exchange']
        if source_queue is not None:
            return source_queue
    return default

然后我将它用于这样的子任务:

my_task.apply_async(args=('my', 'args'), queue=get_source_queue(default='foo_queue'))


我不知道这是否是最好的方式......也许有一些内置于芹菜中的东西说"使用与源队列相同的队列" (?)但是,上述工作。

相关问题