README.rst 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. =====================================================================
  2. Database-backed Periodic Tasks
  3. =====================================================================
  4. |build-status| |coverage| |license| |wheel| |pyversion| |pyimp|
  5. :Version: 1.4.0
  6. :Web: http://django-celery-beat.readthedocs.io/
  7. :Download: http://pypi.python.org/pypi/django-celery-beat
  8. :Source: http://github.com/celery/django-celery-beat
  9. :Keywords: django, celery, beat, periodic task, cron, scheduling
  10. About
  11. =====
  12. This extension enables you to store the periodic task schedule in the
  13. database.
  14. The periodic tasks can be managed from the Django Admin interface, where you
  15. can create, edit and delete periodic tasks and how often they should run.
  16. Using the Extension
  17. ===================
  18. Usage and installation instructions for this extension are available
  19. from the `Celery documentation`_:
  20. http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#using-custom-scheduler-classes
  21. .. _`Celery documentation`:
  22. http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#using-custom-scheduler-classes
  23. Important Warning about Time Zones
  24. ==================================
  25. .. warning::
  26. If you change the Django ``TIME_ZONE`` setting your periodic task schedule
  27. will still be based on the old timezone.
  28. To fix that you would have to reset the "last run time" for each periodic
  29. task::
  30. >>> from django_celery_beat.models import PeriodicTask, PeriodicTasks
  31. >>> PeriodicTask.objects.all().update(last_run_at=None)
  32. >>> for task in PeriodicTask.objects.all():
  33. >>> PeriodicTasks.changed(task)
  34. Note that this will reset the state as if the periodic tasks have never run
  35. before.
  36. Models
  37. ======
  38. - ``django_celery_beat.models.PeriodicTask``
  39. This model defines a single periodic task to be run.
  40. It must be associated with a schedule, which defines how often the task should
  41. run.
  42. - ``django_celery_beat.models.IntervalSchedule``
  43. A schedule that runs at a specific interval (e.g. every 5 seconds).
  44. - ``django_celery_beat.models.CrontabSchedule``
  45. A schedule with fields like entries in cron:
  46. ``minute hour day-of-week day_of_month month_of_year``.
  47. - ``django_celery_beat.models.PeriodicTasks``
  48. This model is only used as an index to keep track of when the schedule has
  49. changed.
  50. Whenever you update a ``PeriodicTask`` a counter in this table is also
  51. incremented, which tells the ``celery beat`` service to reload the schedule
  52. from the database.
  53. If you update periodic tasks in bulk, you will need to update the counter
  54. manually::
  55. >>> from django_celery_beat.models import PeriodicTasks
  56. >>> PeriodicTasks.changed()
  57. Example creating interval-based periodic task
  58. ---------------------------------------------
  59. To create a periodic task executing at an interval you must first
  60. create the interval object::
  61. >>> from django_celery_beat.models import PeriodicTask, IntervalSchedule
  62. # executes every 10 seconds.
  63. >>> schedule, created = IntervalSchedule.objects.get_or_create(
  64. ... every=10,
  65. ... period=IntervalSchedule.SECONDS,
  66. ... )
  67. That's all the fields you need: a period type and the frequency.
  68. You can choose between a specific set of periods:
  69. - ``IntervalSchedule.DAYS``
  70. - ``IntervalSchedule.HOURS``
  71. - ``IntervalSchedule.MINUTES``
  72. - ``IntervalSchedule.SECONDS``
  73. - ``IntervalSchedule.MICROSECONDS``
  74. .. note::
  75. If you have multiple periodic tasks executing every 10 seconds,
  76. then they should all point to the same schedule object.
  77. There's also a "choices tuple" available should you need to present this
  78. to the user::
  79. >>> IntervalSchedule.PERIOD_CHOICES
  80. Now that we have defined the schedule object, we can create the periodic task
  81. entry::
  82. >>> PeriodicTask.objects.create(
  83. ... interval=schedule, # we created this above.
  84. ... name='Importing contacts', # simply describes this periodic task.
  85. ... task='proj.tasks.import_contacts', # name of task.
  86. ... )
  87. Note that this is a very basic example, you can also specify the arguments
  88. and keyword arguments used to execute the task, the ``queue`` to send it
  89. to[*], and set an expiry time.
  90. Here's an example specifying the arguments, note how JSON serialization is
  91. required::
  92. >>> import json
  93. >>> from datetime import datetime, timedelta
  94. >>> PeriodicTask.objects.create(
  95. ... interval=schedule, # we created this above.
  96. ... name='Importing contacts', # simply describes this periodic task.
  97. ... task='proj.tasks.import_contacts', # name of task.
  98. ... args=json.dumps(['arg1', 'arg2']),
  99. ... kwargs=json.dumps({
  100. ... 'be_careful': True,
  101. ... }),
  102. ... expires=datetime.utcnow() + timedelta(seconds=30)
  103. ... )
  104. .. [*] you can also use low-level AMQP routing using the ``exchange`` and
  105. ``routing_key`` fields.
  106. Example creating crontab-based periodic task
  107. --------------------------------------------
  108. A crontab schedule has the fields: ``minute``, ``hour``, ``day_of_week``,
  109. ``day_of_month`` and ``month_of_year`, so if you want the equivalent
  110. of a ``30 * * * *`` (execute every 30 minutes) crontab entry you specify::
  111. >>> from django_celery_beat.models import CrontabSchedule, PeriodicTask
  112. >>> schedule, _ = CrontabSchedule.objects.get_or_create(
  113. ... minute='30',
  114. ... hour='*',
  115. ... day_of_week='*',
  116. ... day_of_month='*',
  117. ... month_of_year='*',
  118. ... timezone=pytz.timezone('Canada/Pacific')
  119. ... )
  120. The crontab schedule is linked to a specific timezone using the 'timezone' input parameter.
  121. Then to create a periodic task using this schedule, use the same approach as
  122. the interval-based periodic task earlier in this document, but instead
  123. of ``interval=schedule``, specify ``crontab=schedule``::
  124. >>> PeriodicTask.objects.create(
  125. ... crontab=schedule,
  126. ... name='Importing contacts',
  127. ... task='proj.tasks.import_contacts',
  128. ... )
  129. Temporarily disable a periodic task
  130. -----------------------------------
  131. You can use the ``enabled`` flag to temporarily disable a periodic task::
  132. >>> periodic_task.enabled = False
  133. >>> periodic_task.save()
  134. Installation
  135. ============
  136. You can install django-celery-beat either via the Python Package Index (PyPI)
  137. or from source.
  138. To install using `pip`,::
  139. $ pip install -U django-celery-beat
  140. Downloading and installing from source
  141. --------------------------------------
  142. Download the latest version of django-celery-beat from
  143. http://pypi.python.org/pypi/django-celery-beat
  144. You can install it by doing the following,::
  145. $ tar xvfz django-celery-beat-0.0.0.tar.gz
  146. $ cd django-celery-beat-0.0.0
  147. $ python setup.py build
  148. # python setup.py install
  149. The last command must be executed as a privileged user if
  150. you are not currently using a virtualenv.
  151. Using the development version
  152. -----------------------------
  153. With pip
  154. ~~~~~~~~
  155. You can install the latest snapshot of django-celery-beat using the following
  156. pip command::
  157. $ pip install https://github.com/celery/django-celery-beat/zipball/master#egg=django-celery-beat
  158. TZ Awareness:
  159. -------------
  160. If you have a project that is time zone naive, you can set `DJANGO_CELERY_BEAT_TZ_AWARE=False` in your settings file.
  161. .. |build-status| image:: https://secure.travis-ci.org/celery/django-celery-beat.svg?branch=master
  162. :alt: Build status
  163. :target: https://travis-ci.org/celery/django-celery-beat
  164. .. |coverage| image:: https://codecov.io/github/celery/django-celery-beat/coverage.svg?branch=master
  165. :target: https://codecov.io/github/celery/django-celery-beat?branch=master
  166. .. |license| image:: https://img.shields.io/pypi/l/django-celery-beat.svg
  167. :alt: BSD License
  168. :target: https://opensource.org/licenses/BSD-3-Clause
  169. .. |wheel| image:: https://img.shields.io/pypi/wheel/django-celery-beat.svg
  170. :alt: django-celery-beat can be installed via wheel
  171. :target: http://pypi.python.org/pypi/django-celery-beat/
  172. .. |pyversion| image:: https://img.shields.io/pypi/pyversions/django-celery-beat.svg
  173. :alt: Supported Python versions.
  174. :target: http://pypi.python.org/pypi/django-celery-beat/
  175. .. |pyimp| image:: https://img.shields.io/pypi/implementation/django-celery-beat.svg
  176. :alt: Support Python implementations.
  177. :target: http://pypi.python.org/pypi/django-celery-beat/