periodic-tasks.rst 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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.decorators import periodic_task
  8. from datetime import timedelta
  9. @periodic_task(run_every=timedelta(seconds=30))
  10. def every_30_seconds(\*\*kwargs):
  11. logger = self.get_logger(\*\*kwargs)
  12. logger.info("Running periodic task!")
  13. If you want a little more control over when the task is executed, for example,
  14. a particular time of day or day of the week, you can use the ``crontab`` schedule
  15. type:
  16. .. code-block:: python
  17. from celery.task.schedules import crontab
  18. from celery.decorators import periodic_task
  19. @periodoc_task(run_every=crontab(hour=7, minute=30, day_of_week=1))
  20. def every_monday_morning(\*\*kwargs):
  21. logger = self.get_logger(\*\*kwargs)
  22. logger.info("Execute every Monday at 7:30AM.")
  23. If you want to use periodic tasks you need to start the ``celerybeat``
  24. service. You have to make sure only one instance of this server is running at
  25. any time, or else you will end up with multiple executions of the same task.
  26. To start the ``celerybeat`` service::
  27. $ celerybeat
  28. You can also start ``celerybeat`` with ``celeryd`` by using the ``-B`` option,
  29. this is convenient if you only have one server::
  30. $ celeryd -B