signals.rst 16 KB

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