Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between different ways to create celery task

I am very confused by looking at different ways of creating a celery task. On the surface they all work the same So, Can someone explain what is the difference between these.

1.

from myproject.tasks import app  @app.task def foo():     pass 

2.

from celery import task  @task def foo():     pass 

3.

from celery import shared_task  @shared_task def foo():     pass 

I know by a little bit of googling that the difference between the 1nd and 3rd one is shared_task is used when you don't have a concrete app instance. Can someone elaborate more on that and when is the second one is used?

like image 672
MOntu Avatar asked Feb 03 '19 19:02

MOntu


People also ask

What is difference between Apply_async and delay?

delay() has comes preconfigured and only requires arguments to be passed to the task — that's sufficient for most basic needs. Apply_async is more complex, but also more powerful then preconfigured delay. It is always better to use apply_async with specifically set options for maximum flexibility.

How do you create a celery task in Python?

Create a Celery Task Once an application is created, create a task.py file and create a task. The tasks are the regular Python functions that are called with the Celery. For example - We create a function that will print the 1 to 10 integer number. Now create a view in the view.py file.


1 Answers

Don't use #2 unless you are using celery v3. If you are using celery v4, use #1.

Use #3 in instances where you are writing a reusable library or django app. For example, if you are writing an open source set of tasks that allow you to manage aws ec2 instances using celery, you would use shared_task so that the tasks could be run on celery, but you would leave it to the person using your library to configure celery for themselves.

Use #1 if you are writing for your own project and there is no concern for re-use.

like image 55
2ps Avatar answered Oct 23 '22 14:10

2ps