celery.contrib.methods

Task decorator that supports creating tasks out of methods.

Examples


1. from celery.contrib.methods import task

3. class X(object):

5. @task()
6. def add(self, x, y):
7. return x + y

or with any task decorator:


1. from celery.contrib.methods import task_method

3. class X(object):

5. @app.task(filter=task_method)
6. def add(self, x, y):
7. return x + y

注解

The task must use the new Task base class (celery.Task), and the old base class using classmethods (celery.task.Task, celery.task.base.Task).

This means that you have to use the task decorator from a Celery app instance, and not the old-API:


1. from celery import task       # BAD
2. from celery.task import task  # ALSO BAD

4. # GOOD:
5. app = Celery(...)

7. @app.task(filter=task_method)
8. def foo(self): pass

10. # ALSO GOOD:
11. from celery import current_app

13. @current_app.task(filter=task_method)
14. def foo(self): pass

16. # ALSO GOOD:
17. from celery import shared_task

19. @shared_task(filter=task_method)
20. def foo(self): pass

Caveats

  • Automatic naming won’t be able to know what the class name is.

The name will still be module_name + task_name, so two methods with the same name in the same module will collide so that only one task can run:

```

  1. class A(object):

  2. @task()

  3. def add(self, x, y):
  4. return x + y

  5. class B(object):

  6. @task()

  7. def add(self, x, y):
  8. return x + y ```

would have to be written as:

```

  1. class A(object):
  2. @task(name='A.add')
  3. def add(self, x, y):
  4. return x + y

  5. class B(object):

  6. @task(name='B.add')
  7. def add(self, x, y):
  8. return x + y ```

class celery.contrib.methods.task_method(task, *args,* **kwargs*)[源代码]

celery.contrib.methods.task(*args,* **kwargs*)[源代码]