signals.rst 14 KB

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