signals.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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_shutdown
  237. worker_shutdown
  238. ~~~~~~~~~~~~~~~
  239. Dispatched when the worker is about to shut down.
  240. Beat Signals
  241. ------------
  242. .. signal:: beat_init
  243. beat_init
  244. ~~~~~~~~~
  245. Dispatched when :program:`celery beat` starts (either standalone or embedded).
  246. Sender is the :class:`celery.beat.Service` instance.
  247. .. signal:: beat_embedded_init
  248. beat_embedded_init
  249. ~~~~~~~~~~~~~~~~~~
  250. Dispatched in addition to the :signal:`beat_init` signal when :program:`celery
  251. beat` is started as an embedded process. Sender is the
  252. :class:`celery.beat.Service` instance.
  253. Eventlet Signals
  254. ----------------
  255. .. signal:: eventlet_pool_started
  256. eventlet_pool_started
  257. ~~~~~~~~~~~~~~~~~~~~~
  258. Sent when the eventlet pool has been started.
  259. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  260. .. signal:: eventlet_pool_preshutdown
  261. eventlet_pool_preshutdown
  262. ~~~~~~~~~~~~~~~~~~~~~~~~~
  263. Sent when the worker shutdown, just before the eventlet pool
  264. is requested to wait for remaining workers.
  265. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  266. .. signal:: eventlet_pool_postshutdown
  267. eventlet_pool_postshutdown
  268. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  269. Sent when the pool has been joined and the worker is ready to shutdown.
  270. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  271. .. signal:: eventlet_pool_apply
  272. eventlet_pool_apply
  273. ~~~~~~~~~~~~~~~~~~~
  274. Sent whenever a task is applied to the pool.
  275. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  276. Provides arguments:
  277. * target
  278. The target function.
  279. * args
  280. Positional arguments.
  281. * kwargs
  282. Keyword arguments.
  283. Logging Signals
  284. ---------------
  285. .. signal:: setup_logging
  286. setup_logging
  287. ~~~~~~~~~~~~~
  288. Celery won't configure the loggers if this signal is connected,
  289. so you can use this to completely override the logging configuration
  290. with your own.
  291. If you would like to augment the logging configuration setup by
  292. Celery then you can use the :signal:`after_setup_logger` and
  293. :signal:`after_setup_task_logger` signals.
  294. Provides arguments:
  295. * loglevel
  296. The level of the logging object.
  297. * logfile
  298. The name of the logfile.
  299. * format
  300. The log format string.
  301. * colorize
  302. Specify if log messages are colored or not.
  303. .. signal:: after_setup_logger
  304. after_setup_logger
  305. ~~~~~~~~~~~~~~~~~~
  306. Sent after the setup of every global logger (not task loggers).
  307. Used to augment logging configuration.
  308. Provides arguments:
  309. * logger
  310. The logger object.
  311. * loglevel
  312. The level of the logging object.
  313. * logfile
  314. The name of the logfile.
  315. * format
  316. The log format string.
  317. * colorize
  318. Specify if log messages are colored or not.
  319. .. signal:: after_setup_task_logger
  320. after_setup_task_logger
  321. ~~~~~~~~~~~~~~~~~~~~~~~
  322. Sent after the setup of every single task logger.
  323. Used to augment logging configuration.
  324. Provides arguments:
  325. * logger
  326. The logger object.
  327. * loglevel
  328. The level of the logging object.
  329. * logfile
  330. The name of the logfile.
  331. * format
  332. The log format string.
  333. * colorize
  334. Specify if log messages are colored or not.
  335. Command signals
  336. ---------------
  337. .. signal:: user_preload_options
  338. user_preload_options
  339. ~~~~~~~~~~~~~~~~~~~~
  340. This signal is sent after any of the Celery command line programs
  341. are finished parsing the user preload options.
  342. It can be used to add additional command-line arguments to the
  343. :program:`celery` umbrella command:
  344. .. code-block:: python
  345. from celery import Celery
  346. from celery import signals
  347. from celery.bin.base import Option
  348. app = Celery()
  349. app.user_options['preload'].add(Option(
  350. '--monitoring', action='store_true',
  351. help='Enable our external monitoring utility, blahblah',
  352. ))
  353. @signals.user_preload_options.connect
  354. def handle_preload_options(options, **kwargs):
  355. if options['monitoring']:
  356. enable_monitoring()
  357. Sender is the :class:`~celery.bin.base.Command` instance, which depends
  358. on what program was called (e.g. for the umbrella command it will be
  359. a :class:`~celery.bin.celery.CeleryCommand`) object).
  360. Provides arguments:
  361. * app
  362. The app instance.
  363. * options
  364. Mapping of the parsed user preload options (with default values).
  365. Deprecated Signals
  366. ------------------
  367. .. signal:: task_sent
  368. task_sent
  369. ~~~~~~~~~
  370. This signal is deprecated, please use :signal:`after_task_publish` instead.