periodic-tasks.rst 10 KB

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