periodic-tasks.rst 1.6 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 use ``crontab`` to set
  18. the ``run_every`` property:
  19. .. code-block:: python
  20. from celery.task import PeriodicTask
  21. from celery.task.schedules import crontab
  22. class EveryMondayMorningTask(PeriodicTask):
  23. run_every = crontab(hour=7, minute=30, day_of_week=1)
  24. def run(self, **kwargs):
  25. logger = self.get_logger(**kwargs)
  26. logger.info("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