periodic-tasks.rst 10 KB

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