periodic-tasks.rst 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. ================
  2. Periodic Tasks
  3. ================
  4. You can schedule tasks to run at intervals like ``cron``.
  5. Here's an example of a periodic task:
  6. .. code-block:: python
  7. from celery.task import PeriodicTask
  8. from celery.registry import tasks
  9. from datetime import timedelta
  10. class MyPeriodicTask(PeriodicTask):
  11. run_every = timedelta(seconds=30)
  12. def run(self, **kwargs):
  13. logger = self.get_logger(**kwargs)
  14. logger.info("Running periodic task!")
  15. >>> tasks.register(MyPeriodicTask)
  16. If you want a little more control over when the task is executed, for example,
  17. a particular time of day or day of the week, you can subclass a ``ScheduledTask``:
  18. .. code-block:: python
  19. from celery.task import ScheduledTask
  20. class EveryMondayMorningTask(ScheduledTask):
  21. hour = 7
  22. minute = 30
  23. day_of_week = 1
  24. def run(self, **kwargs):
  25. logger = self.get_logger(**kwargs)
  26. logger.info("This will execute every Monday at 7:30AM.")
  27. If you want to use periodic tasks you need to start the ``celerybeat``
  28. service. You have to make sure only one instance of this server is running at
  29. any time, or else you will end up with multiple executions of the same task.
  30. To start the ``celerybeat`` service::
  31. $ celerybeat
  32. or if using Django::
  33. $ python manage.py celerybeat
  34. You can also start ``celerybeat`` with ``celeryd`` by using the ``-B`` option,
  35. this is convenient if you only have one server::
  36. $ celeryd -B
  37. or if using Django::
  38. $ python manage.py celeryd -B