signals.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. .. _signals:
  2. =======
  3. Signals
  4. =======
  5. .. contents::
  6. :local:
  7. Signals allows decoupled applications to receive notifications when
  8. certain actions occur elsewhere in the application.
  9. Celery ships with many signals that you application can hook into
  10. to augment behavior of certain actions.
  11. .. _signal-basics:
  12. Basics
  13. ======
  14. Several kinds of events trigger signals, you can connect to these signals
  15. to perform actions as they trigger.
  16. Example connecting to the :signal:`after_task_publish` signal:
  17. .. code-block:: python
  18. from celery.signals import after_task_publish
  19. @after_task_publish.connect
  20. def task_sent_handler(sender=None, body=None, **kwargs):
  21. print('after_task_publish for task id {body[id]}'.format(
  22. body=body,
  23. ))
  24. Some signals also have a sender which you can filter by. For example the
  25. :signal:`after_task_publish` signal uses the task name as a sender, so by
  26. providing the ``sender`` argument to
  27. :class:`~celery.utils.dispatch.signal.Signal.connect` you can
  28. connect your handler to be called every time a task with name `"proj.tasks.add"`
  29. is published:
  30. .. code-block:: python
  31. @after_task_publish.connect(sender='proj.tasks.add')
  32. def task_sent_handler(sender=None, body=None, **kwargs):
  33. print('after_task_publish for task id {body[id]}'.format(
  34. body=body,
  35. ))
  36. Signals use the same implementation as django.core.dispatch. As a result other
  37. keyword parameters (e.g. signal) are passed to all signal handlers by default.
  38. The best practice for signal handlers is to accept arbitrary keyword
  39. arguments (i.e. ``**kwargs``). That way new celery versions can add additional
  40. arguments without breaking user code.
  41. .. _signal-ref:
  42. Signals
  43. =======
  44. Task Signals
  45. ------------
  46. .. signal:: before_task_publish
  47. before_task_publish
  48. ~~~~~~~~~~~~~~~~~~~
  49. .. versionadded:: 3.1
  50. Dispatched before a task is published.
  51. Note that this is executed in the process sending the task.
  52. Sender is the name of the task being sent.
  53. Provides arguements:
  54. * body
  55. Task message body.
  56. This is a mapping containing the task message fields
  57. (see :ref:`task-message-protocol-v1`).
  58. * exchange
  59. Name of the exchange to send to or a :class:`~kombu.Exchange` object.
  60. * routing_key
  61. Routing key to use when sending the message.
  62. * headers
  63. Application headers mapping (can be modified).
  64. * properties
  65. Message properties (can be modified)
  66. * declare
  67. List of entities (:class:`~kombu.Exchange`,
  68. :class:`~kombu.Queue` or :class:~`kombu.binding` to declare before
  69. publishing the message. Can be modified.
  70. * retry_policy
  71. Mapping of retry options. Can be any argument to
  72. :meth:`kombu.Connection.ensure` and can be modified.
  73. .. signal:: after_task_publish
  74. after_task_publish
  75. ~~~~~~~~~~~~~~~~~~
  76. Dispatched when a task has been sent to the broker.
  77. Note that this is executed in the process that sent the task.
  78. Sender is the name of the task being sent.
  79. Provides arguments:
  80. * body
  81. The task message body, see :ref:`task-message-protocol-v1`
  82. for a reference of possible fields that can be defined.
  83. * exchange
  84. Name of the exchange or :class:`~kombu.Exchange` object used.
  85. * routing_key
  86. Routing key used.
  87. .. signal:: task_prerun
  88. task_prerun
  89. ~~~~~~~~~~~
  90. Dispatched before a task is executed.
  91. Sender is the task class being executed.
  92. Provides arguments:
  93. * task_id
  94. Id of the task to be executed.
  95. * task
  96. The task being executed.
  97. * args
  98. the tasks positional arguments.
  99. * kwargs
  100. The tasks keyword arguments.
  101. .. signal:: task_postrun
  102. task_postrun
  103. ~~~~~~~~~~~~
  104. Dispatched after a task has been executed.
  105. Sender is the task class executed.
  106. Provides arguments:
  107. * task_id
  108. Id of the task to be executed.
  109. * task
  110. The task being executed.
  111. * args
  112. The tasks positional arguments.
  113. * kwargs
  114. The tasks keyword arguments.
  115. * retval
  116. The return value of the task.
  117. * state
  118. Name of the resulting state.
  119. .. signal:: task_success
  120. task_success
  121. ~~~~~~~~~~~~
  122. Dispatched when a task succeeds.
  123. Sender is the task class executed.
  124. Provides arguments
  125. * result
  126. Return value of the task.
  127. .. signal:: task_failure
  128. task_failure
  129. ~~~~~~~~~~~~
  130. Dispatched when a task fails.
  131. Sender is the task class executed.
  132. Provides arguments:
  133. * task_id
  134. Id of the task.
  135. * exception
  136. Exception instance raised.
  137. * args
  138. Positional arguments the task was called with.
  139. * kwargs
  140. Keyword arguments the task was called with.
  141. * traceback
  142. Stack trace object.
  143. * einfo
  144. The :class:`celery.datastructures.ExceptionInfo` instance.
  145. .. signal:: task_revoked
  146. task_revoked
  147. ~~~~~~~~~~~~
  148. Dispatched when a task is revoked/terminated by the worker.
  149. Sender is the task class revoked/terminated.
  150. Provides arguments:
  151. * request
  152. This is a :class:`~celery.worker.job.Request` instance, and not
  153. ``task.request``. When using the prefork pool this signal
  154. is dispatched in the parent process, so ``task.request`` is not available
  155. and should not be used. Use this object instead, which should have many
  156. of the same fields.
  157. * terminated
  158. Set to :const:`True` if the task was terminated.
  159. * signum
  160. Signal number used to terminate the task. If this is :const:`None` and
  161. terminated is :const:`True` then :sig:`TERM` should be assumed.
  162. * expired
  163. Set to :const:`True` if the task expired.
  164. Worker Signals
  165. --------------
  166. .. signal:: celeryd_after_setup
  167. celeryd_after_setup
  168. ~~~~~~~~~~~~~~~~~~~
  169. This signal is sent after the worker instance is set up,
  170. but before it calls run. This means that any queues from the :option:`-Q`
  171. option is enabled, logging has been set up and so on.
  172. It can be used to e.g. add custom queues that should always be consumed
  173. from, disregarding the :option:`-Q` option. Here's an example
  174. that sets up a direct queue for each worker, these queues can then be
  175. used to route a task to any specific worker:
  176. .. code-block:: python
  177. from celery.signals import celeryd_after_setup
  178. @celeryd_after_setup.connect
  179. def setup_direct_queue(sender, instance, **kwargs):
  180. queue_name = '{0}.dq'.format(sender) # sender is the hostname of the worker
  181. instance.app.amqp.queues.select_add(queue_name)
  182. Provides arguments:
  183. * sender
  184. Hostname of the worker.
  185. * instance
  186. This is the :class:`celery.apps.worker.Worker` instance to be initialized.
  187. Note that only the :attr:`app` and :attr:`hostname` attributes have been
  188. set so far, and the rest of ``__init__`` has not been executed.
  189. * conf
  190. The configuration of the current app.
  191. .. signal:: celeryd_init
  192. celeryd_init
  193. ~~~~~~~~~~~~
  194. This is the first signal sent when :program:`celery worker` starts up.
  195. The ``sender`` is the host name of the worker, so this signal can be used
  196. to setup worker specific configuration:
  197. .. code-block:: python
  198. from celery.signals import celeryd_init
  199. @celeryd_init.connect(sender='worker12.example.com')
  200. def configure_worker12(conf=None, **kwargs):
  201. conf.CELERY_DEFAULT_RATE_LIMIT = '10/m'
  202. or to set up configuration for multiple workers you can omit specifying a
  203. sender when you connect:
  204. .. code-block:: python
  205. from celery.signals import celeryd_init
  206. @celeryd_init.connect
  207. def configure_workers(sender=None, conf=None, **kwargs):
  208. if sender in ('worker1.example.com', 'worker2.example.com'):
  209. conf.CELERY_DEFAULT_RATE_LIMIT = '10/m'
  210. if sender == 'worker3.example.com':
  211. conf.CELERYD_PREFETCH_MULTIPLIER = 0
  212. Provides arguments:
  213. * sender
  214. Hostname of the worker.
  215. * instance
  216. This is the :class:`celery.apps.worker.Worker` instance to be initialized.
  217. Note that only the :attr:`app` and :attr:`hostname` attributes have been
  218. set so far, and the rest of ``__init__`` has not been executed.
  219. * conf
  220. The configuration of the current app.
  221. * options
  222. Options passed to the worker from command-line arguments (including
  223. defaults).
  224. .. signal:: worker_init
  225. worker_init
  226. ~~~~~~~~~~~
  227. Dispatched before the worker is started.
  228. .. signal:: worker_ready
  229. worker_ready
  230. ~~~~~~~~~~~~
  231. Dispatched when the worker is ready to accept work.
  232. .. signal:: worker_process_init
  233. worker_process_init
  234. ~~~~~~~~~~~~~~~~~~~
  235. Dispatched by each new pool worker process when it starts.
  236. .. signal:: worker_process_shutdown
  237. worker_process_shutdown
  238. ~~~~~~~~~~~~~~~~~~~
  239. Dispatched by each new pool worker process when it is about to shut down.
  240. .. signal:: worker_shutdown
  241. worker_shutdown
  242. ~~~~~~~~~~~~~~~
  243. Dispatched when the worker is about to shut down.
  244. Beat Signals
  245. ------------
  246. .. signal:: beat_init
  247. beat_init
  248. ~~~~~~~~~
  249. Dispatched when :program:`celery beat` starts (either standalone or embedded).
  250. Sender is the :class:`celery.beat.Service` instance.
  251. .. signal:: beat_embedded_init
  252. beat_embedded_init
  253. ~~~~~~~~~~~~~~~~~~
  254. Dispatched in addition to the :signal:`beat_init` signal when :program:`celery
  255. beat` is started as an embedded process. Sender is the
  256. :class:`celery.beat.Service` instance.
  257. Eventlet Signals
  258. ----------------
  259. .. signal:: eventlet_pool_started
  260. eventlet_pool_started
  261. ~~~~~~~~~~~~~~~~~~~~~
  262. Sent when the eventlet pool has been started.
  263. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  264. .. signal:: eventlet_pool_preshutdown
  265. eventlet_pool_preshutdown
  266. ~~~~~~~~~~~~~~~~~~~~~~~~~
  267. Sent when the worker shutdown, just before the eventlet pool
  268. is requested to wait for remaining workers.
  269. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  270. .. signal:: eventlet_pool_postshutdown
  271. eventlet_pool_postshutdown
  272. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  273. Sent when the pool has been joined and the worker is ready to shutdown.
  274. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  275. .. signal:: eventlet_pool_apply
  276. eventlet_pool_apply
  277. ~~~~~~~~~~~~~~~~~~~
  278. Sent whenever a task is applied to the pool.
  279. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  280. Provides arguments:
  281. * target
  282. The target function.
  283. * args
  284. Positional arguments.
  285. * kwargs
  286. Keyword arguments.
  287. Logging Signals
  288. ---------------
  289. .. signal:: setup_logging
  290. setup_logging
  291. ~~~~~~~~~~~~~
  292. Celery won't configure the loggers if this signal is connected,
  293. so you can use this to completely override the logging configuration
  294. with your own.
  295. If you would like to augment the logging configuration setup by
  296. Celery then you can use the :signal:`after_setup_logger` and
  297. :signal:`after_setup_task_logger` signals.
  298. Provides arguments:
  299. * loglevel
  300. The level of the logging object.
  301. * logfile
  302. The name of the logfile.
  303. * format
  304. The log format string.
  305. * colorize
  306. Specify if log messages are colored or not.
  307. .. signal:: after_setup_logger
  308. after_setup_logger
  309. ~~~~~~~~~~~~~~~~~~
  310. Sent after the setup of every global logger (not task loggers).
  311. Used to augment logging configuration.
  312. Provides arguments:
  313. * logger
  314. The logger object.
  315. * loglevel
  316. The level of the logging object.
  317. * logfile
  318. The name of the logfile.
  319. * format
  320. The log format string.
  321. * colorize
  322. Specify if log messages are colored or not.
  323. .. signal:: after_setup_task_logger
  324. after_setup_task_logger
  325. ~~~~~~~~~~~~~~~~~~~~~~~
  326. Sent after the setup of every single task logger.
  327. Used to augment logging configuration.
  328. Provides arguments:
  329. * logger
  330. The logger object.
  331. * loglevel
  332. The level of the logging object.
  333. * logfile
  334. The name of the logfile.
  335. * format
  336. The log format string.
  337. * colorize
  338. Specify if log messages are colored or not.
  339. Command signals
  340. ---------------
  341. .. signal:: user_preload_options
  342. user_preload_options
  343. ~~~~~~~~~~~~~~~~~~~~
  344. This signal is sent after any of the Celery command line programs
  345. are finished parsing the user preload options.
  346. It can be used to add additional command-line arguments to the
  347. :program:`celery` umbrella command:
  348. .. code-block:: python
  349. from celery import Celery
  350. from celery import signals
  351. from celery.bin.base import Option
  352. app = Celery()
  353. app.user_options['preload'].add(Option(
  354. '--monitoring', action='store_true',
  355. help='Enable our external monitoring utility, blahblah',
  356. ))
  357. @signals.user_preload_options.connect
  358. def handle_preload_options(options, **kwargs):
  359. if options['monitoring']:
  360. enable_monitoring()
  361. Sender is the :class:`~celery.bin.base.Command` instance, which depends
  362. on what program was called (e.g. for the umbrella command it will be
  363. a :class:`~celery.bin.celery.CeleryCommand`) object).
  364. Provides arguments:
  365. * app
  366. The app instance.
  367. * options
  368. Mapping of the parsed user preload options (with default values).
  369. Deprecated Signals
  370. ------------------
  371. .. signal:: task_sent
  372. task_sent
  373. ~~~~~~~~~
  374. This signal is deprecated, please use :signal:`after_task_publish` instead.