如何为 Celery 任务添加自定义 ID 以便稍后撤销任务?

bel*_*lek 4 python django celery

我想创建延迟任务,如果有一些条件,我需要找到该任务并撤销它。

这就是我创建任务的方式:

notify_before_departure.apply_async(
            args=(user.fcm_registration_token, booking.bus_stop_from.title,),
            eta=notification_time,
        )
Run Code Online (Sandbox Code Playgroud)

那么,是否有任何属性apply_async可以让我定义自定义 ID,稍后可以使用该属性来撤销这个确切的任务?像这样的东西:

# create task
notify_before_departure.apply_async(
                args=(user.fcm_registration_token, booking.bus_stop_from.title,),
                eta=notification_time,
                custom_id=booking.id
            )
# revoke if needed
from celery.task.control import revoke 
revoke(booking.id, terminate=True)
Run Code Online (Sandbox Code Playgroud)

bel*_*lek 7

好吧,在阅读常见问题解答后回答我自己的问题:

notify_before_departure.apply_async(
            args=(user.fcm_registration_token, booking.bus_stop_from.title,),
            eta=notification_time,
            task_id=f"departure_push_for_booking_{booking.id}"
        )
Run Code Online (Sandbox Code Playgroud)

进而:

revoke(f"departure_push_for_booking_{booking.id}", terminate=True)
Run Code Online (Sandbox Code Playgroud)