工程結構說明:源文件下載請訪問https://i.cnblogs.com/Files.aspxpython
__init__.py:實例化celery,並加載配置模塊redis
celeryconfig.py:配置模塊app
task1:任務1,實現加法spa
task2:任務2,實現乘法3d
app.py:應用,任務生產者日誌
一、__init__.py:實例化celery,並加載配置模塊code
# -*- coding: utf-8 -*- from celery import Celery myapp=Celery('demo') #經過Celery實例加載配置模塊celeryconfig.py myapp.config_from_object('celerywithconfig.celeryconfig')
二、celeryconfig.py:配置模塊blog
# -*- coding: utf-8 -*- ''' Created on 2019年8月28日 @author: lenovo ''' BROKER_URL='redis://localhost:6379/1' CELERY_RESULT_BACKEND='redis://localhost:6379/2' CELERY_TIMEZONE='Asia/Shanghai'#不指定時區的話默認採用UTC #導入指定的任務模塊 CELERY_IMPORTS=( 'celerywithconfig.task1', 'celerywithconfig.task2', )
三、task1:任務1,實現加法ip
# -*- coding: utf-8 -*- ''' Created on 2019年8月28日 @author: lenovo ''' import time #從__init__.py中導入實例化的Celery myapp from celerywithconfig import myapp @myapp.task def add(x,y): time.sleep(3) return x+y
四、task2:任務2,實現乘法utf-8
# -*- coding: utf-8 -*- ''' Created on 2019年8月28日 @author: lenovo ''' import time from celerywithconfig import myapp @myapp.task def multiply(x,y): time.sleep(4) return x * y
五、app.py:應用,任務生產者
# -*- coding: utf-8 -*- ''' Created on 2019年8月28日 @author: lenovo ''' from celerywithconfig import task1 from celerywithconfig import task2 task1.add.delay(2, 4) task2.multiply.delay(4, 5) print 'end...'
六、啓動worker,監放任務
cd到src路徑下,執行命令python -m celery -A celerywithconfig worker --loglevel=info
七、執行app.py,生產任務
八、查看任務消費狀況:worker日誌顯示同時接收到了2個任務,並分別進行了消費:
九、查看任務消費狀況:消費結果成功保存在backend中: