Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add an on_failure callback to a celery task created with the task decorator?

Tags:

celery

I'm pretty sure this can only be done if I create my own task class, but I'd like to know if anyone else has found a way to do this.

like image 956
abrugh Avatar asked Jan 10 '14 23:01

abrugh


2 Answers

You can provide the function directly to the decorator:

def fun(self, exc, task_id, args, kwargs, einfo):
    print('Failed!')

@task(name="foo:my_task", on_failure=fun)
def add(x, y):
    raise KeyError()
like image 165
Nolan Conaway Avatar answered Nov 18 '22 22:11

Nolan Conaway


Here is a full solution (works for Celery 4+):

import celery
from celery.task import task

class MyBaseClassForTask(celery.Task):

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        # exc (Exception) - The exception raised by the task.
        # args (Tuple) - Original arguments for the task that failed.
        # kwargs (Dict) - Original keyword arguments for the task that failed.
        print('{0!r} failed: {1!r}'.format(task_id, exc))

@task(name="foo:my_task", base=MyBaseClassForTask)
def add(x, y):
    raise KeyError()

Resources:

  • http://docs.celeryproject.org/en/latest/userguide/tasks.html#task-inheritance
  • http://docs.celeryproject.org/en/latest/reference/celery.app.task.html#celery.app.task.Task.on_failure
  • http://docs.celeryproject.org/en/latest/userguide/tasks.html#abstract-classes
like image 24
illagrenan Avatar answered Nov 18 '22 20:11

illagrenan