celery.contrib.methods

Task decorator that supports creating tasks out of methods.

Examples

  1. from celery.contrib.methods import task
  2. class X(object):
  3. @task()
  4. def add(self, x, y):
  5. return x + y

or with any task decorator:

  1. from celery.contrib.methods import task_method
  2. class X(object):
  3. @app.task(filter=task_method)
  4. def add(self, x, y):
  5. 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
  3. # GOOD:
  4. app = Celery(...)
  5. @app.task(filter=task_method)
  6. def foo(self): pass
  7. # ALSO GOOD:
  8. from celery import current_app
  9. @current_app.task(filter=task_method)
  10. def foo(self): pass
  11. # ALSO GOOD:
  12. from celery import shared_task
  13. @shared_task(filter=task_method)
  14. 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*)[源代码]