Warm tip: This article is reproduced from serverfault.com, please click

Revoke a queued task if the related object does not exist

发布于 2020-12-03 08:47:01

I am trying to delete a queued task (using Celery) which is triggered when an object is created. If, the task is to be triggered 5 min before an event and the object is deleted already, the queued messages remain.

task.py

@app.task
def send_notification(abc):
    # do some stuff with abc
    # return something

models.py

class ABC(models.Model):
    description = models.TextField()

views.py

def abc(request):
    # create the ABC object
    send_after=timezone.now() + timedelta(minutes=5)
    send_notification.apply_async(eta=send_after)
    # return something

So, when the object ABC is deleted right after creating one, the related queued message should also be revoked.

Any idea on how to handle this ?

Questioner
twingo
Viewed
0
twingo 2020-12-06 05:59:02

I fixed this by passing the object id to the task and not the object, and so an extra line in the task:

@app.task
def send_notification(abc_id):
    try:
        abc_obj = ABC.objects.get(id=abc_id)
    except ObjectDoesnotExist:
        return

    # do some stuff with abc
    # return something