Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canonical Celery single file hello world

I cannot seem to find a single file anywhere online that will run from start to finish with Celery and Python to demonstrate it so I tried to make one. For some reason this is not working, I am new to Celery. In test_celery.py I added the content below:

from celery import Celery
import time

app = Celery(
    'test_celery'
    ,broker= 'redis://localhost/0',
    backend='redis://localhost/1'
)

@app.task
def add(x, y):
    time.sleep(2)
    return x + y

if __name__ == '__main__':
    result = add.delay(4, 4)
    print( result.get() )

Then I ran the redis server on localhost and at the console entered:

celery -A test_celery worker --loglevel=info

So, now the worker is listening and I try to run python test_celery.py thinking that I should see my wonderful 8 in the console output. In the log of the worker console, I see [2015-01-02 16:53:08,807: INFO/MainProcess] Task test_celery.add[2c6b19c0-3a3f-45d2-8024-64e112fa3419] succeeded in 1.9970000002067536s: 8 which is as expected but the call to result.get hangs in the main program console.

I must be missing something basic here, if anyone could help that would be great.

like image 515
user25064 Avatar asked Oct 19 '22 19:10

user25064


1 Answers

The solution is to simply set the result backend with the app.conf.update call rather than in the constructor of the Celery object.

I found the solution to this problem in this post of this thread on the Celery GitHub page. It remains an open issue (for now)

Solution

from celery import Celery
import time

app = Celery(
    'test_celery'
    ,broker= 'redis://localhost/0'
)

app.conf.update(
    CELERY_RESULT_BACKEND = 'redis://localhost/1'
)

@app.task
def add(x, y):
    time.sleep(2)
    return x + y

if __name__ == '__main__':
    result = add.delay(4, 4)
    print( result.get() )

Works as expected.

like image 110
user25064 Avatar answered Oct 22 '22 23:10

user25064