Difference between task and shared_task in Celery?

Asked

Viewed 638 times

1

I am implementing a time-consuming process in my Django application that needs to be run asynchronously to avoid timeout in the browser. For this, I chose to use the Celery to perform the time-consuming function in the background.

I read some articles recommending using both the Developer @task as for the developer @shared_task, but I didn’t quite understand the difference between the two. I tried both and saw no difference in my application.

1 answer

2


The decorator task, by default share tasks between apps:

app1 = Celery()
@app1.task
def test_task():
    pass

app2 = Celery()

print('test_task.name in app1.tasks.keys(): ' + str(test_task.name in app1.tasks.keys()),  
      'test_task.name in app2.tasks.keys(): ' + str(test_task.name in app2.tasks.keys()),  sep='\n')

Exit:

test_task.name in app1.tasks.keys(): True
test_task.name in app2.tasks.keys(): True

But note that the name test_task always referred to the instance linked to the "app1"

test_task.app is app1
Out[13]: True

test_task.app is app2
Out[14]: False

The Developer @shared_task returns a proxy that always connects to the instance of the app in use:

app1 = Celery() 

@shared_task 
def test_task(): 
    pass 

print (test_task.app is app1)

Exit:

True 

Now let’s do:

app2 = Celery() 
print('test_task.app is app1: '+str(test_task.app is app1), 
      'test_task.app is app2: '+str(test_task.app is app2), sep='\n' )

Exit:

test_task.app is app1: False
test_task.app is app2: True

This way the @shared_task decorator is more useful for libraries and reusable apps.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.