periodic-tasks.rst 11 KB

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