该篇着重介绍一下如何调用任务,队列路由。详见Celery中文手册
一、在项目中使用Celery
-
我的项目目录:
TestCelery/ ├── proj │ ├── celeryconfig.py │ ├── celery.py │ ├── init.py │ └── tasks.py └── test.py
-
celery.py文件内容如下:
from celery import Celery # 创建celery实例 app = Celery('demo') app.config_from_object('proj.celeryconfig') # 自动搜索任务 app.autodiscover_tasks(['proj'])
-
celeryconfig.p模块内容如下:
from kombu import Exchange, Queue BROKER_URL = 'redis://:332572@127.0.0.1:6379/1' CELERY_RESULT_BACKEND = 'redis://:332572@127.0.0.1:6379/2'
-
tasks.py模块内容如下:
from proj.celery import app as celery_app # 创建任务函数 @celery_app.task def my_task1(): print("任务函数(my_task1)正在执行....") @celery_app.task def my_task2(): print("任务函数(my_task2)正在执行....") @celery_app.task def my_task3(): print("任务函数(my_task3)正在执行....")
-
启动worker:如图
celery -A proj worker -l info
在终端按 ctrl+c 即可关闭worker
二、调用任务Calling Task
-
调用任务,最简单的方法就是使用delay()方法:
my_task.delay(2, 2)
-
也可以使用apply_async()方法,该方法可让我们设置一些任务执行的参数,例如,任务多久之后才执行,任务被发送到那个队列中等等.
my_task.apply_async((2