Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of bind = True keyword in celery?

What is the meaning of bind=True in below celery code? When to use it and when not?

@app.task(bind=True) def send_twitter_status(self, oauth, tweet):     try:         twitter = Twitter(oauth)         twitter.update_status(tweet)     except (Twitter.FailWhaleError, Twitter.LoginError) as exc:         raise self.retry(exc=exc) 
like image 580
Devang Padhiyar Avatar asked Feb 27 '19 06:02

Devang Padhiyar


People also ask

What is Shared_task in Celery?

The "shared_task" decorator allows creation of Celery tasks for reusable apps as it doesn't need the instance of the Celery app. It is also easier way to define a task as you don't need to import the Celery app instance.

How do I register a task on Celery?

Register a task in the task registry. The task will be automatically instantiated if not already an instance. Name must be configured prior to registration. Unregister task by name.

What is Celery in Python used for?

Celery is an open-source Python library which is used to run the tasks asynchronously. It is a task queue that holds the tasks and distributes them to the workers in a proper manner. It is primarily focused on real-time operation but also supports scheduling (run regular interval tasks).

How does Celery backend work?

Celery communicates via messages, usually using a broker to mediate between clients and workers. To initiate a task the client adds a message to the queue, the broker then delivers that message to a worker.


2 Answers

Just a small addition to other answers. As already stated, bound tasks have access to the task instance. One use case when this is needed are retries:

@celery.task(bind=True, max_retries=5) def retrying(self):     try:         return 1/0     except Exception:         self.retry(countdown=5) 

Another use case is when you want to define custom states for your tasks and be able to set it during task execution:

@celery.task(bind=True) def show_progress(self, n):     for i in range(n):         self.update_state(state='PROGRESS', meta={'current': i, 'total': n}) 
like image 183
Tomáš Linhart Avatar answered Sep 29 '22 10:09

Tomáš Linhart


Bound tasks

A task being bound means the first argument to the task will always be the task instance (self), just like Python bound methods:

logger = get_task_logger(__name__)  @task(bind=True) def add(self, x, y):     logger.info(self.request.id) 
like image 37
Devang Padhiyar Avatar answered Sep 29 '22 11:09

Devang Padhiyar