signals.rst 14 KB

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