| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628 | .. _signals:=======Signals=======.. contents::    :local:Signals allows decoupled applications to receive notifications whencertain actions occur elsewhere in the application.Celery ships with many signals that you application can hook intoto augment behavior of certain actions... _signal-basics:Basics======Several kinds of events trigger signals, you can connect to these signalsto perform actions as they trigger.Example connecting to the :signal:`after_task_publish` signal:.. code-block:: python    from celery.signals import after_task_publish    @after_task_publish.connect    def task_sent_handler(sender=None, body=None, **kwargs):        print('after_task_publish for task id {body[id]}'.format(            body=body,        ))Some signals also have a sender which you can filter by. For example the:signal:`after_task_publish` signal uses the task name as a sender, so byproviding the ``sender`` argument to:class:`~celery.utils.dispatch.signal.Signal.connect` you canconnect your handler to be called every time a task with name `"proj.tasks.add"`is published:.. code-block:: python    @after_task_publish.connect(sender='proj.tasks.add')    def task_sent_handler(sender=None, body=None, **kwargs):        print('after_task_publish for task id {body[id]}'.format(            body=body,        ))Signals use the same implementation as django.core.dispatch. As a result otherkeyword parameters (e.g. signal) are passed to all signal handlers by default.The best practice for signal handlers is to accept arbitrary keywordarguments (i.e. ``**kwargs``).  That way new celery versions can add additionalarguments without breaking user code... _signal-ref:Signals=======Task Signals------------.. signal:: before_task_publishbefore_task_publish~~~~~~~~~~~~~~~~~~~.. versionadded:: 3.1Dispatched before a task is published.Note that this is executed in the process sending the task.Sender is the name of the task being sent.Provides arguements:* body    Task message body.    This is a mapping containing the task message fields    (see :ref:`task-message-protocol-v1`).* exchange    Name of the exchange to send to or a :class:`~kombu.Exchange` object.* routing_key    Routing key to use when sending the message.* headers    Application headers mapping (can be modified).* properties    Message properties (can be modified)* declare    List of entities (:class:`~kombu.Exchange`,    :class:`~kombu.Queue` or :class:~`kombu.binding` to declare before    publishing the message.  Can be modified.* retry_policy    Mapping of retry options.  Can be any argument to    :meth:`kombu.Connection.ensure` and can be modified... signal:: after_task_publishafter_task_publish~~~~~~~~~~~~~~~~~~Dispatched when a task has been sent to the broker.Note that this is executed in the process that sent the task.Sender is the name of the task being sent.Provides arguments:* body    The task message body, see :ref:`task-message-protocol-v1`    for a reference of possible fields that can be defined.* exchange    Name of the exchange or :class:`~kombu.Exchange` object used.* routing_key    Routing key used... signal:: task_preruntask_prerun~~~~~~~~~~~Dispatched before a task is executed.Sender is the task class being executed.Provides arguments:* task_id    Id of the task to be executed.* task    The task being executed.* args    the tasks positional arguments.* kwargs    The tasks keyword arguments... signal:: task_postruntask_postrun~~~~~~~~~~~~Dispatched after a task has been executed.Sender is the task class executed.Provides arguments:* task_id    Id of the task to be executed.* task    The task being executed.* args    The tasks positional arguments.* kwargs    The tasks keyword arguments.* retval    The return value of the task.* state    Name of the resulting state... signal:: task_successtask_success~~~~~~~~~~~~Dispatched when a task succeeds.Sender is the task class executed.Provides arguments* result    Return value of the task... signal:: task_failuretask_failure~~~~~~~~~~~~Dispatched when a task fails.Sender is the task class executed.Provides arguments:* task_id    Id of the task.* exception    Exception instance raised.* args    Positional arguments the task was called with.* kwargs    Keyword arguments the task was called with.* traceback    Stack trace object.* einfo    The :class:`celery.datastructures.ExceptionInfo` instance... signal:: task_revokedtask_revoked~~~~~~~~~~~~Dispatched when a task is revoked/terminated by the worker.Sender is the task class revoked/terminated.Provides arguments:* request    This is a :class:`~celery.worker.job.Request` instance, and not    ``task.request``.   When using the prefork pool this signal    is dispatched in the parent process, so ``task.request`` is not available    and should not be used.  Use this object instead, which should have many    of the same fields.* terminated    Set to :const:`True` if the task was terminated.* signum    Signal number used to terminate the task. If this is :const:`None` and    terminated is :const:`True` then :sig:`TERM` should be assumed.* expired  Set to :const:`True` if the task expired.App Signals-----------.. signal:: import_modulesimport_modules~~~~~~~~~~~~~~This signal is sent when a program (worker, beat, shell) etc, asksfor modules in the :setting:`CELERY_INCLUDE` and :setting:`CELERY_IMPORTS`settings to be imported.Sender is the app instance.Worker Signals--------------.. signal:: celeryd_after_setupceleryd_after_setup~~~~~~~~~~~~~~~~~~~This signal is sent after the worker instance is set up,but before it calls run.  This means that any queues from the :option:`-Q`option is enabled, logging has been set up and so on.It can be used to e.g. add custom queues that should always be consumedfrom, disregarding the :option:`-Q` option.  Here's an examplethat sets up a direct queue for each worker, these queues can then beused to route a task to any specific worker:.. code-block:: python    from celery.signals import celeryd_after_setup    @celeryd_after_setup.connect    def setup_direct_queue(sender, instance, **kwargs):        queue_name = '{0}.dq'.format(sender)  # sender is the nodename of the worker        instance.app.amqp.queues.select_add(queue_name)Provides arguments:* sender  Hostname of the worker.* instance    This is the :class:`celery.apps.worker.Worker` instance to be initialized.    Note that only the :attr:`app` and :attr:`hostname` (nodename) attributes have been    set so far, and the rest of ``__init__`` has not been executed.* conf    The configuration of the current app... signal:: celeryd_initceleryd_init~~~~~~~~~~~~This is the first signal sent when :program:`celery worker` starts up.The ``sender`` is the host name of the worker, so this signal can be usedto setup worker specific configuration:.. code-block:: python    from celery.signals import celeryd_init    @celeryd_init.connect(sender='worker12@example.com')    def configure_worker12(conf=None, **kwargs):        conf.CELERY_DEFAULT_RATE_LIMIT = '10/m'or to set up configuration for multiple workers you can omit specifying asender when you connect:.. code-block:: python    from celery.signals import celeryd_init    @celeryd_init.connect    def configure_workers(sender=None, conf=None, **kwargs):        if sender in ('worker1@example.com', 'worker2@example.com'):            conf.CELERY_DEFAULT_RATE_LIMIT = '10/m'        if sender == 'worker3@example.com':            conf.CELERYD_PREFETCH_MULTIPLIER = 0Provides arguments:* sender  Nodename of the worker.* instance    This is the :class:`celery.apps.worker.Worker` instance to be initialized.    Note that only the :attr:`app` and :attr:`hostname` (nodename) attributes have been    set so far, and the rest of ``__init__`` has not been executed.* conf    The configuration of the current app.* options    Options passed to the worker from command-line arguments (including    defaults)... signal:: worker_initworker_init~~~~~~~~~~~Dispatched before the worker is started... signal:: worker_readyworker_ready~~~~~~~~~~~~Dispatched when the worker is ready to accept work... signal:: worker_process_initworker_process_init~~~~~~~~~~~~~~~~~~~Dispatched in all pool child processes when they start.Note that handlers attached to this signal must not be blockingfor more than 4 seconds, or the process will be killed assumingit failed to start... signal:: worker_process_shutdownworker_process_shutdown~~~~~~~~~~~~~~~~~~~~~~~Dispatched in all pool child processes just before they exit.Note: There is no guarantee that this signal will be dispatched,similarly to finally blocks it's impossible to guarantee that handlerswill be called at shutdown, and if called it may be interrupted during.Provides arguments:* pid    The pid of the child process that is about to shutdown.* exitcode    The exitcode that will be used when the child process exits... signal:: worker_shutdownworker_shutdown~~~~~~~~~~~~~~~Dispatched when the worker is about to shut down.Beat Signals------------.. signal:: beat_initbeat_init~~~~~~~~~Dispatched when :program:`celery beat` starts (either standalone or embedded).Sender is the :class:`celery.beat.Service` instance... signal:: beat_embedded_initbeat_embedded_init~~~~~~~~~~~~~~~~~~Dispatched in addition to the :signal:`beat_init` signal when :program:`celerybeat` is started as an embedded process.  Sender is the:class:`celery.beat.Service` instance.Eventlet Signals----------------.. signal:: eventlet_pool_startedeventlet_pool_started~~~~~~~~~~~~~~~~~~~~~Sent when the eventlet pool has been started.Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance... signal:: eventlet_pool_preshutdowneventlet_pool_preshutdown~~~~~~~~~~~~~~~~~~~~~~~~~Sent when the worker shutdown, just before the eventlet poolis requested to wait for remaining workers.Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance... signal:: eventlet_pool_postshutdowneventlet_pool_postshutdown~~~~~~~~~~~~~~~~~~~~~~~~~~Sent when the pool has been joined and the worker is ready to shutdown.Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance... signal:: eventlet_pool_applyeventlet_pool_apply~~~~~~~~~~~~~~~~~~~Sent whenever a task is applied to the pool.Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.Provides arguments:* target    The target function.* args    Positional arguments.* kwargs    Keyword arguments.Logging Signals---------------.. signal:: setup_loggingsetup_logging~~~~~~~~~~~~~Celery won't configure the loggers if this signal is connected,so you can use this to completely override the logging configurationwith your own.If you would like to augment the logging configuration setup byCelery then you can use the :signal:`after_setup_logger` and:signal:`after_setup_task_logger` signals.Provides arguments:* loglevel    The level of the logging object.* logfile    The name of the logfile.* format    The log format string.* colorize    Specify if log messages are colored or not... signal:: after_setup_loggerafter_setup_logger~~~~~~~~~~~~~~~~~~Sent after the setup of every global logger (not task loggers).Used to augment logging configuration.Provides arguments:* logger    The logger object.* loglevel    The level of the logging object.* logfile    The name of the logfile.* format    The log format string.* colorize    Specify if log messages are colored or not... signal:: after_setup_task_loggerafter_setup_task_logger~~~~~~~~~~~~~~~~~~~~~~~Sent after the setup of every single task logger.Used to augment logging configuration.Provides arguments:* logger    The logger object.* loglevel    The level of the logging object.* logfile    The name of the logfile.* format    The log format string.* colorize    Specify if log messages are colored or not.Command signals---------------.. signal:: user_preload_optionsuser_preload_options~~~~~~~~~~~~~~~~~~~~This signal is sent after any of the Celery command line programsare finished parsing the user preload options.It can be used to add additional command-line arguments to the:program:`celery` umbrella command:.. code-block:: python    from celery import Celery    from celery import signals    from celery.bin.base import Option    app = Celery()    app.user_options['preload'].add(Option(        '--monitoring', action='store_true',        help='Enable our external monitoring utility, blahblah',    ))    @signals.user_preload_options.connect    def handle_preload_options(options, **kwargs):        if options['monitoring']:            enable_monitoring()Sender is the :class:`~celery.bin.base.Command` instance, which dependson what program was called (e.g. for the umbrella command it will bea :class:`~celery.bin.celery.CeleryCommand`) object).Provides arguments:* app    The app instance.* options    Mapping of the parsed user preload options (with default values).Deprecated Signals------------------.. signal:: task_senttask_sent~~~~~~~~~This signal is deprecated, please use :signal:`after_task_publish` instead.
 |