tasks.rst 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. =======
  2. Tasks
  3. =======
  4. A task is a class that encapsulates a function and its execution options.
  5. With a function ``create_user``, that takes two arguments: ``username`` and
  6. ``password``, you can create a task like this:
  7. .. code-block:: python
  8. from celery.task import Task
  9. class CreateUserTask(Task):
  10. def run(self, username, password):
  11. create_user(username, password)
  12. For convenience there is a shortcut decorator that turns any function into
  13. a task, ``celery.decorators.task``:
  14. .. code-block:: python
  15. from celery.decorators import task
  16. from django.contrib.auth import User
  17. @task()
  18. def create_user(username, password):
  19. User.objects.create(username=username, password=password)
  20. Note the parens after ``@task()`` the task decorator takes any execution
  21. options the ``Task`` class does:
  22. .. code-block:: python
  23. @task(serializer="json")
  24. def create_user(username, password):
  25. User.objects.create(username=username, password=password)
  26. An alternative way to use the decorator is to give the function as an argument
  27. instead, but if you do this be sure to set the return values ``__name__``
  28. attribute, so pickle is able to find it in reverse:
  29. .. code-block:: python
  30. create_user_task = task()(create_user)
  31. create_user_task.__name__ = "create_user_task"
  32. Default keyword arguments
  33. =========================
  34. Celery supports a set of default arguments that can be forwarded to any task.
  35. task can choose not to take these, or only list the ones it want
  36. (the worker will do the right thing).
  37. The current default keyword arguments are:
  38. * logfile
  39. The currently used log file, can be passed on to ``self.get_logger``
  40. to gain access to the workers log file. See `Logging`_.
  41. * loglevel
  42. The current loglevel used.
  43. * task_id
  44. The unique id of the executing task.
  45. * task_name
  46. Name of the executing task.
  47. * task_retries
  48. How many times the current task has been retried.
  49. (an integer starting a ``0``).
  50. Logging
  51. =======
  52. You can use the workers logger to add some diagnostic output to
  53. the worker log:
  54. .. code-block:: python
  55. from celery.decorators import task
  56. @task()
  57. def add(x, y, **kwargs):
  58. logger = add.get_logger(**kwargs)
  59. logger.info("Adding %s + %s" % (x, y))
  60. return x + y
  61. There are several logging levels available, and the workers ``loglevel``
  62. setting decides whether they will be sent to the log file or not.