periodic-tasks.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. .. _guide-beat:
  2. ================
  3. Periodic Tasks
  4. ================
  5. .. contents::
  6. :local:
  7. Introduction
  8. ============
  9. :program:`celery beat` is a scheduler. It kicks off tasks at regular intervals,
  10. which are then executed by the worker nodes available in the cluster.
  11. By default the entries are taken from the :setting:`CELERYBEAT_SCHEDULE` setting,
  12. but custom stores can also be used, like storing the entries
  13. in an SQL database.
  14. You have to ensure only a single scheduler is running for a schedule
  15. at a time, otherwise you would end up with duplicate tasks. Using
  16. a centralized approach means the schedule does not have to be synchronized,
  17. and the service can operate without using locks.
  18. .. _beat-timezones:
  19. Time Zones
  20. ==========
  21. The periodic task schedules uses the UTC time zone by default,
  22. but you can change the time zone used using the :setting:`CELERY_TIMEZONE`
  23. setting.
  24. The `pytz`_ library is recommended when setting a default timezone.
  25. If :mod:`pytz` is not installed it will fallback to the mod:`dateutil`
  26. library, which depends on a system timezone file being available for
  27. the timezone selected.
  28. Timezone definitions change frequently, so for the best results
  29. an up to date :mod:`pytz` installation should be used.
  30. .. code-block:: bash
  31. $ pip install -U pytz
  32. An example time zone could be `Europe/London`:
  33. .. code-block:: python
  34. CELERY_TIMEZONE = 'Europe/London'
  35. The default scheduler (storing the schedule in the :file:`celerybeat-schedule`
  36. file) will automatically detect that the time zone has changed, and so will
  37. reset the schedule itself, but other schedulers may not be so smart (e.g. the
  38. Django database scheduler, see below) and in that case you will have to reset the
  39. schedule manually.
  40. .. admonition:: Django Users
  41. Celery recommends and is compatible with the new ``USE_TZ`` setting introduced
  42. in Django 1.4.
  43. For Django users the time zone specified in the ``TIME_ZONE`` setting
  44. will be used, or you can specify a custom time zone for Celery alone
  45. by using the :setting:`CELERY_TIMEZONE` setting.
  46. The database scheduler will not reset when timezone related settings
  47. change, so you must do this manually:
  48. .. code-block:: bash
  49. $ python manage.py shell
  50. >>> from djcelery.models import PeriodicTask
  51. >>> PeriodicTask.objects.update(last_run_at=None)
  52. .. _`pytz`: http://pypi.python.org/pypi/pytz/
  53. .. _beat-entries:
  54. Entries
  55. =======
  56. To schedule a task periodically you have to add an entry to the
  57. :setting:`CELERYBEAT_SCHEDULE` setting.
  58. Example: Run the `tasks.add` task every 30 seconds.
  59. .. code-block:: python
  60. from datetime import timedelta
  61. CELERYBEAT_SCHEDULE = {
  62. 'runs-every-30-seconds': {
  63. 'task': 'tasks.add',
  64. 'schedule': timedelta(seconds=30),
  65. 'args': (16, 16)
  66. },
  67. }
  68. CELERY_TIMEZONE = 'UTC'
  69. Using a :class:`~datetime.timedelta` for the schedule means the task will
  70. be executed 30 seconds after `celery beat` starts, and then every 30 seconds
  71. after the last run. A crontab like schedule also exists, see the section
  72. on `Crontab schedules`_.
  73. .. _beat-entry-fields:
  74. Available Fields
  75. ----------------
  76. * `task`
  77. The name of the task to execute.
  78. * `schedule`
  79. The frequency of execution.
  80. This can be the number of seconds as an integer, a
  81. :class:`~datetime.timedelta`, or a :class:`~celery.schedules.crontab`.
  82. You can also define your own custom schedule types, by extending the
  83. interface of :class:`~celery.schedules.schedule`.
  84. * `args`
  85. Positional arguments (:class:`list` or :class:`tuple`).
  86. * `kwargs`
  87. Keyword arguments (:class:`dict`).
  88. * `options`
  89. Execution options (:class:`dict`).
  90. This can be any argument supported by
  91. :meth:`~celery.task.base.Task.apply_async`,
  92. e.g. `exchange`, `routing_key`, `expires`, and so on.
  93. * `relative`
  94. By default :class:`~datetime.timedelta` schedules are scheduled
  95. "by the clock". This means the frequency is rounded to the nearest
  96. second, minute, hour or day depending on the period of the timedelta.
  97. If `relative` is true the frequency is not rounded and will be
  98. relative to the time when :program:`celery beat` was started.
  99. .. _beat-crontab:
  100. Crontab schedules
  101. =================
  102. If you want more control over when the task is executed, for
  103. example, a particular time of day or day of the week, you can use
  104. the :class:`~celery.schedules.crontab` schedule type:
  105. .. code-block:: python
  106. from celery.schedules import crontab
  107. CELERYBEAT_SCHEDULE = {
  108. # Executes every Monday morning at 7:30 A.M
  109. 'every-monday-morning': {
  110. 'task': 'tasks.add',
  111. 'schedule': crontab(hour=7, minute=30, day_of_week=1),
  112. 'args': (16, 16),
  113. },
  114. }
  115. The syntax of these crontab expressions are very flexible. Some examples:
  116. +-----------------------------------------+--------------------------------------------+
  117. | **Example** | **Meaning** |
  118. +-----------------------------------------+--------------------------------------------+
  119. | ``crontab()`` | Execute every minute. |
  120. +-----------------------------------------+--------------------------------------------+
  121. | ``crontab(minute=0, hour=0)`` | Execute daily at midnight. |
  122. +-----------------------------------------+--------------------------------------------+
  123. | ``crontab(minute=0, hour='*/3')`` | Execute every three hours: |
  124. | | 3am, 6am, 9am, noon, 3pm, 6pm, 9pm. |
  125. +-----------------------------------------+--------------------------------------------+
  126. | ``crontab(minute=0,`` | Same as previous. |
  127. | ``hour=[0,3,6,9,12,15,18,21])`` | |
  128. +-----------------------------------------+--------------------------------------------+
  129. | ``crontab(minute='*/15')`` | Execute every 15 minutes. |
  130. +-----------------------------------------+--------------------------------------------+
  131. | ``crontab(day_of_week='sunday')`` | Execute every minute (!) at Sundays. |
  132. +-----------------------------------------+--------------------------------------------+
  133. | ``crontab(minute='*',`` | Same as previous. |
  134. | ``hour='*',`` | |
  135. | ``day_of_week='sun')`` | |
  136. +-----------------------------------------+--------------------------------------------+
  137. | ``crontab(minute='*/10',`` | Execute every ten minutes, but only |
  138. | ``hour='3,17,22',`` | between 3-4 am, 5-6 pm and 10-11 pm on |
  139. | ``day_of_week='thu,fri')`` | Thursdays or Fridays. |
  140. +-----------------------------------------+--------------------------------------------+
  141. | ``crontab(minute=0, hour='*/2,*/3')`` | Execute every even hour, and every hour |
  142. | | divisible by three. This means: |
  143. | | at every hour *except*: 1am, |
  144. | | 5am, 7am, 11am, 1pm, 5pm, 7pm, |
  145. | | 11pm |
  146. +-----------------------------------------+--------------------------------------------+
  147. | ``crontab(minute=0, hour='*/5')`` | Execute hour divisible by 5. This means |
  148. | | that it is triggered at 3pm, not 5pm |
  149. | | (since 3pm equals the 24-hour clock |
  150. | | value of "15", which is divisible by 5). |
  151. +-----------------------------------------+--------------------------------------------+
  152. | ``crontab(minute=0, hour='*/3,8-17')`` | Execute every hour divisible by 3, and |
  153. | | every hour during office hours (8am-5pm). |
  154. +-----------------------------------------+--------------------------------------------+
  155. | ``crontab(day_of_month='2')`` | Execute on the second day of every month. |
  156. | | |
  157. +-----------------------------------------+--------------------------------------------+
  158. | ``crontab(day_of_month='2-30/3')`` | Execute on every even numbered day. |
  159. | | |
  160. +-----------------------------------------+--------------------------------------------+
  161. | ``crontab(day_of_month='1-7,15-21')`` | Execute on the first and third weeks of |
  162. | | the month. |
  163. +-----------------------------------------+--------------------------------------------+
  164. | ``crontab(day_of_month='11',`` | Execute on 11th of May every year. |
  165. | ``month_of_year='5')`` | |
  166. +-----------------------------------------+--------------------------------------------+
  167. | ``crontab(month_of_year='*/3')`` | Execute on the first month of every |
  168. | | quarter. |
  169. +-----------------------------------------+--------------------------------------------+
  170. See :class:`celery.schedules.crontab` for more documentation.
  171. .. _beat-starting:
  172. Starting the Scheduler
  173. ======================
  174. To start the :program:`celery beat` service:
  175. .. code-block:: bash
  176. $ celery beat
  177. You can also start embed `beat` inside the worker by enabling
  178. workers `-B` option, this is convenient if you only intend to
  179. use one worker node:
  180. .. code-block:: bash
  181. $ celery worker -B
  182. Beat needs to store the last run times of the tasks in a local database
  183. file (named `celerybeat-schedule` by default), so it needs access to
  184. write in the current directory, or alternatively you can specify a custom
  185. location for this file:
  186. .. code-block:: bash
  187. $ celery beat -s /home/celery/var/run/celerybeat-schedule
  188. .. note::
  189. To daemonize beat see :ref:`daemonizing`.
  190. .. _beat-custom-schedulers:
  191. Using custom scheduler classes
  192. ------------------------------
  193. Custom scheduler classes can be specified on the command line (the `-S`
  194. argument). The default scheduler is :class:`celery.beat.PersistentScheduler`,
  195. which is simply keeping track of the last run times in a local database file
  196. (a :mod:`shelve`).
  197. `django-celery` also ships with a scheduler that stores the schedule in the
  198. Django database:
  199. .. code-block:: bash
  200. $ celery beat -S djcelery.schedulers.DatabaseScheduler
  201. Using `django-celery`'s scheduler you can add, modify and remove periodic
  202. tasks from the Django Admin.