如何从celery 队列中按名称删除任务

xxhby3vn  于 2021-06-08  发布在  Redis
关注(0)|答案(1)|浏览(363)

我正在尝试从celery 队列中删除具有特定名称的所有当前排队的任务。从官方文件中,我知道我可以检查工人,通过查找他们的姓名,然后获取他们的身份证来撤销任务,比如:

def drop_celery_task(options):
    def _get_tasks_id(workers: list, tasks_ids: list, task_name: str):
        """
        Get task ids with the given name included inside the given `workers` tasks.
        {'worker1.example.com': [
             {'name': 'tasks.sleeptask', 'id': '32666e9b-809c-41fa-8e93-5ae0c80afbbf',
              'args': '(8,)', 'kwargs': '{}'}]
        }
        """

        for worker in workers:
            if not workers[worker]:
                continue
            for _task in workers[worker]:
                if _task["name"].split(".")[-1] == task_name:
                    tasks_ids.append(_task["id"])

    task_name = options.drop_celery_task["name"]
    i = Inspect(app=celery_app)  # Inspect all nodes.
    registered = i.registered()
    if not registered:
        raise Exception("No registered tasks found")

    if not any(task_name == worker.split(".")[-1] for worker in chain(*list(registered.values()))):
        raise Exception(f"Task not registered: {task_name}")

    tasks_ids = []
    _get_tasks_id(i.active(), tasks_ids, task_name)
    _get_tasks_id(i.scheduled(), tasks_ids, task_name)
    _get_tasks_id(i.reserved(), tasks_ids, task_name)

    if tasks_ids:
        for task_id in tasks_ids:
            Control(app=celery_app).revoke(task_id)
    else:
        logging.info(f"No active/scheduled/registered task found with the name {task_name}")

但是这段代码只撤销celery 工人获取或预获取的任务,而不是仍然在队列中的任务(使用redis作为后端)。关于如何使用celery 命令删除redis中的任务,或者阻止工作人员接受具有给定名称的任务,有什么建议吗?

axr492tv

axr492tv1#

最后,我在redis中用我想要的名称标识了任务的id(使用redis客户端,而不是celery 命令),然后通过 Control(app=celery_app).revoke(task_id) 通信。在redis中,队列是带有队列名称的键下的列表对象。

相关问题