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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With