Problems with the new celery style api

I have a class that extends Task celery. It works fine with the old API, but I'm having trouble converting it to the new API.

 # In app/tasks.py from celery import Celery, Task celery = Celery() @celery.task class CustomTask(Task): def run(self, x): try: # do something except Exception, e: self.retry(args=[x], exc=e) 

And then I run the task like this:

 CustomTask().apply_async(args=[x], queue='q1') 

And I get an error message -

 TypeError: run() takes exactly 2 arguments (1 given) 

This SO answer seems to be doing the exact same thing, and it was adopted as intended, it works. Can someone help me and explain to me why my code is not working?

EDIT

This works if I call a task other than the class name -

 name = 'app.tasks.CustomTask2' 

But if I save the task name in the same way as the full class name, it does not work

 name = 'app.tasks.CustomTask' 

But the problem with a different name is that celery has an additional task with the same name as the task class name.

+2
source share
1 answer

The decorator is not used with classes; it is used for functions.

Normally, you do not need to define custom task classes if you do not want to implement the usual behavior.

So either remove the @celery.task decorator, or use it with a function.

Note that the assignment you define here is not related to any instance of celery

Note related to any specific application instance:

 from celery import Task class MyTask(Task): pass 

You can link it later:

 from celery import Celery app = Celery(broker='amqp://') MyTask.bind(app) 

or you can use the base class available in the application:

 from celery import Celery app = Celery(broker='amqp://') class MyTask(app.Task): pass 

The last example is not very clean, since it means that you are completing the application at the module level, this is another reason why using the task decorator with functions is the best practice, and only create custom classes that will be used as a base class for decorated tasks ( @task(base=MyTask) ).

+2
source

All Articles