You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Celery:如何撤销任务组?能否用revoke方法及获取组ID

Can I revoke a Celery task group with app.control.revoke()? How to get the group ID?

Great question! Let's break this down clearly and practically:

1. Can app.control.revoke() handle task groups directly?

No, you can't pass a task group ID directly to app.control.revoke()—this method is built to target individual task IDs only. That said, you can absolutely revoke all tasks in a group—you just need to iterate over each task in the group and revoke them one by one.

2. How to get the task group ID?

There are two common scenarios here, depending on whether you have access to the group result at runtime or need to retrieve it later:

Scenario 1: You just created and executed the group

When you create a task group using Celery's group() function and run it with apply_async(), it returns a GroupResult object. This object has an id attribute that's your task group ID:

from celery import group
from your_app.tasks import your_task

# Create and execute the task group
task_group = group(your_task.s(arg) for arg in [1, 2, 3])
group_result = task_group.apply_async()

# Get the group ID
group_id = group_result.id
print(f"Task Group ID: {group_id}")

Scenario 2: You need to retrieve an existing group later

If you saved the group ID (e.g., in a database or config), you can restore the GroupResult using GroupResult.restore()—this works only if you have a Celery result backend configured (like Redis, PostgreSQL, etc.):

from celery.result import GroupResult

# Replace with your actual saved group ID
saved_group_id = "abc123-xyz456..."
group_result = GroupResult.restore(saved_group_id)

3. How to revoke all tasks in the group

Once you have the GroupResult, extract all individual task IDs from its children attribute, then loop through them to revoke each one:

from celery import current_app

app = current_app

if group_result:
    # Get all task IDs in the group
    task_ids = [task_result.id for task_result in group_result.children]
    
    # Revoke each task
    for task_id in task_ids:
        app.control.revoke(task_id, terminate=True)
        print(f"Revoked task: {task_id}")
else:
    print("Could not find the task group—tasks may have already completed, or your result backend is misconfigured.")

Important Notes:

  • terminate=True will force-kill running tasks. Use this carefully—depending on your task, this could leave resources in an inconsistent state.
  • If a task in the group has already finished executing, revoke() will have no effect on it.
  • Make sure your Celery result backend is properly set up (check CELERY_RESULT_BACKEND in your Django settings) if you need to restore group results later.

内容的提问来源于stack exchange,提问作者Sandeep Prasad Kushwaha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 13:44:09