signals.rst 16 KB

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