signals.rst 12 KB

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