signals.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. App Signals
  165. -----------
  166. .. signal:: import_modules
  167. import_modules
  168. ~~~~~~~~~~~~~~
  169. This signal is sent when a program (worker, beat, shell) etc, asks
  170. for modules in the :setting:`CELERY_INCLUDE` and :setting:`CELERY_IMPORTS`
  171. settings to be imported.
  172. Sender is the app instance.
  173. Worker Signals
  174. --------------
  175. .. signal:: celeryd_after_setup
  176. celeryd_after_setup
  177. ~~~~~~~~~~~~~~~~~~~
  178. This signal is sent after the worker instance is set up,
  179. but before it calls run. This means that any queues from the :option:`-Q`
  180. option is enabled, logging has been set up and so on.
  181. It can be used to e.g. add custom queues that should always be consumed
  182. from, disregarding the :option:`-Q` option. Here's an example
  183. that sets up a direct queue for each worker, these queues can then be
  184. used to route a task to any specific worker:
  185. .. code-block:: python
  186. from celery.signals import celeryd_after_setup
  187. @celeryd_after_setup.connect
  188. def setup_direct_queue(sender, instance, **kwargs):
  189. queue_name = '{0}.dq'.format(sender) # sender is the nodename of the worker
  190. instance.app.amqp.queues.select_add(queue_name)
  191. Provides arguments:
  192. * sender
  193. Hostname of the worker.
  194. * instance
  195. This is the :class:`celery.apps.worker.Worker` instance to be initialized.
  196. Note that only the :attr:`app` and :attr:`hostname` (nodename) attributes have been
  197. set so far, and the rest of ``__init__`` has not been executed.
  198. * conf
  199. The configuration of the current app.
  200. .. signal:: celeryd_init
  201. celeryd_init
  202. ~~~~~~~~~~~~
  203. This is the first signal sent when :program:`celery worker` starts up.
  204. The ``sender`` is the host name of the worker, so this signal can be used
  205. to setup worker specific configuration:
  206. .. code-block:: python
  207. from celery.signals import celeryd_init
  208. @celeryd_init.connect(sender='worker12@example.com')
  209. def configure_worker12(conf=None, **kwargs):
  210. conf.CELERY_DEFAULT_RATE_LIMIT = '10/m'
  211. or to set up configuration for multiple workers you can omit specifying a
  212. sender when you connect:
  213. .. code-block:: python
  214. from celery.signals import celeryd_init
  215. @celeryd_init.connect
  216. def configure_workers(sender=None, conf=None, **kwargs):
  217. if sender in ('worker1@example.com', 'worker2@example.com'):
  218. conf.CELERY_DEFAULT_RATE_LIMIT = '10/m'
  219. if sender == 'worker3@example.com':
  220. conf.CELERYD_PREFETCH_MULTIPLIER = 0
  221. Provides arguments:
  222. * sender
  223. Nodename of the worker.
  224. * instance
  225. This is the :class:`celery.apps.worker.Worker` instance to be initialized.
  226. Note that only the :attr:`app` and :attr:`hostname` (nodename) attributes have been
  227. set so far, and the rest of ``__init__`` has not been executed.
  228. * conf
  229. The configuration of the current app.
  230. * options
  231. Options passed to the worker from command-line arguments (including
  232. defaults).
  233. .. signal:: worker_init
  234. worker_init
  235. ~~~~~~~~~~~
  236. Dispatched before the worker is started.
  237. .. signal:: worker_ready
  238. worker_ready
  239. ~~~~~~~~~~~~
  240. Dispatched when the worker is ready to accept work.
  241. .. signal:: worker_process_init
  242. worker_process_init
  243. ~~~~~~~~~~~~~~~~~~~
  244. Dispatched in all pool child processes when they start.
  245. Note that handlers attached to this signal must not be blocking
  246. for more than 4 seconds, or the process will be killed assuming
  247. it failed to start.
  248. .. signal:: worker_process_shutdown
  249. worker_process_shutdown
  250. ~~~~~~~~~~~~~~~~~~~~~~~
  251. Dispatched in all pool child processes just before they exit.
  252. Note: There is no guarantee that this signal will be dispatched,
  253. similarly to finally blocks it's impossible to guarantee that handlers
  254. will be called at shutdown, and if called it may be interrupted during.
  255. Provides arguments:
  256. * pid
  257. The pid of the child process that is about to shutdown.
  258. * exitcode
  259. The exitcode that will be used when the child process exits.
  260. .. signal:: worker_shutdown
  261. worker_shutdown
  262. ~~~~~~~~~~~~~~~
  263. Dispatched when the worker is about to shut down.
  264. Beat Signals
  265. ------------
  266. .. signal:: beat_init
  267. beat_init
  268. ~~~~~~~~~
  269. Dispatched when :program:`celery beat` starts (either standalone or embedded).
  270. Sender is the :class:`celery.beat.Service` instance.
  271. .. signal:: beat_embedded_init
  272. beat_embedded_init
  273. ~~~~~~~~~~~~~~~~~~
  274. Dispatched in addition to the :signal:`beat_init` signal when :program:`celery
  275. beat` is started as an embedded process. Sender is the
  276. :class:`celery.beat.Service` instance.
  277. Eventlet Signals
  278. ----------------
  279. .. signal:: eventlet_pool_started
  280. eventlet_pool_started
  281. ~~~~~~~~~~~~~~~~~~~~~
  282. Sent when the eventlet pool has been started.
  283. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  284. .. signal:: eventlet_pool_preshutdown
  285. eventlet_pool_preshutdown
  286. ~~~~~~~~~~~~~~~~~~~~~~~~~
  287. Sent when the worker shutdown, just before the eventlet pool
  288. is requested to wait for remaining workers.
  289. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  290. .. signal:: eventlet_pool_postshutdown
  291. eventlet_pool_postshutdown
  292. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  293. Sent when the pool has been joined and the worker is ready to shutdown.
  294. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  295. .. signal:: eventlet_pool_apply
  296. eventlet_pool_apply
  297. ~~~~~~~~~~~~~~~~~~~
  298. Sent whenever a task is applied to the pool.
  299. Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
  300. Provides arguments:
  301. * target
  302. The target function.
  303. * args
  304. Positional arguments.
  305. * kwargs
  306. Keyword arguments.
  307. Logging Signals
  308. ---------------
  309. .. signal:: setup_logging
  310. setup_logging
  311. ~~~~~~~~~~~~~
  312. Celery won't configure the loggers if this signal is connected,
  313. so you can use this to completely override the logging configuration
  314. with your own.
  315. If you would like to augment the logging configuration setup by
  316. Celery then you can use the :signal:`after_setup_logger` and
  317. :signal:`after_setup_task_logger` signals.
  318. Provides arguments:
  319. * loglevel
  320. The level of the logging object.
  321. * logfile
  322. The name of the logfile.
  323. * format
  324. The log format string.
  325. * colorize
  326. Specify if log messages are colored or not.
  327. .. signal:: after_setup_logger
  328. after_setup_logger
  329. ~~~~~~~~~~~~~~~~~~
  330. Sent after the setup of every global logger (not task loggers).
  331. Used to augment logging configuration.
  332. Provides arguments:
  333. * logger
  334. The logger object.
  335. * loglevel
  336. The level of the logging object.
  337. * logfile
  338. The name of the logfile.
  339. * format
  340. The log format string.
  341. * colorize
  342. Specify if log messages are colored or not.
  343. .. signal:: after_setup_task_logger
  344. after_setup_task_logger
  345. ~~~~~~~~~~~~~~~~~~~~~~~
  346. Sent after the setup of every single task logger.
  347. Used to augment logging configuration.
  348. Provides arguments:
  349. * logger
  350. The logger object.
  351. * loglevel
  352. The level of the logging object.
  353. * logfile
  354. The name of the logfile.
  355. * format
  356. The log format string.
  357. * colorize
  358. Specify if log messages are colored or not.
  359. Command signals
  360. ---------------
  361. .. signal:: user_preload_options
  362. user_preload_options
  363. ~~~~~~~~~~~~~~~~~~~~
  364. This signal is sent after any of the Celery command line programs
  365. are finished parsing the user preload options.
  366. It can be used to add additional command-line arguments to the
  367. :program:`celery` umbrella command:
  368. .. code-block:: python
  369. from celery import Celery
  370. from celery import signals
  371. from celery.bin.base import Option
  372. app = Celery()
  373. app.user_options['preload'].add(Option(
  374. '--monitoring', action='store_true',
  375. help='Enable our external monitoring utility, blahblah',
  376. ))
  377. @signals.user_preload_options.connect
  378. def handle_preload_options(options, **kwargs):
  379. if options['monitoring']:
  380. enable_monitoring()
  381. Sender is the :class:`~celery.bin.base.Command` instance, which depends
  382. on what program was called (e.g. for the umbrella command it will be
  383. a :class:`~celery.bin.celery.CeleryCommand`) object).
  384. Provides arguments:
  385. * app
  386. The app instance.
  387. * options
  388. Mapping of the parsed user preload options (with default values).
  389. Deprecated Signals
  390. ------------------
  391. .. signal:: task_sent
  392. task_sent
  393. ~~~~~~~~~
  394. This signal is deprecated, please use :signal:`after_task_publish` instead.