基础使用
- 创建任务
from celery import Celery
app = Celery('demo', broker='redis://127.0.0.1/1', backend='redis://127.0.0.1/2') # 使用redis作为broker和接受返回值
@app.task
def test_task():
print('testing')
- 启动worker
celery -A tasks worker --loglevel=info
- 调用任务
from tasks import test_task
test_task.delay()
项目使用:
编写配置文件
config.py
RESULT_BACKEND='redis://127.0.0.1/2' BROKER_URL = 'redis://127.0.0.1/1'
获取配置参数
import config app = Celery() app.config_from_object('config') # 自动搜索任务 app.autodiscover_tasks(['test_task'])
调用任务
test_task.delay(2, 2)
或
test_task.apply_async((2, 2), queue='my_queue', countdown=10)
# 发送到my_queue队列中10s后执行或
test_task.signatures(countdown=10).delay()
或
group((test_task1.s(2, 2)), (test_task2.s(2, 2)))() # 执行一组任务
或
chain(test_task1.s(2, 2) | test_task2.s(2, 2))() # 执行任务链,第一个任务结果传递给第二个任务
Celery支持AMQP(Advanced Message Queue)所有的路由功能
配置文件添加
task_routes=({ 'proj.tasks.test_task1': {'queue': 'queue1'}, 'proj.tasks.test_task2': {'queue': 'queue1'}, 'proj.tasks.test_task3': {'queue': 'queue2'}, }, )
开启两个队列
celery -A proj worker --loglevel=info -Q queue1 celery -A proj worker --loglevel=info -Q queue2
或
celery -A proj worker --loglevel=info -Q queue1,queue
调用
test_task1.apply_async(queue='queue1')
或
test_task1.delay() test_task2.delay() test_task2.delay()
定时执行某任务(beat调度器)
添加配置信息
beat_schedule = { 'every-5-minute': { 'task': 'proj.tasks.period_task', 'schedule': 5.0, 'args': (16, 16), }, 'add-every-monday-morning': { 'task': 'proj.tasks.period_task', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (16, 16), }, }
开启beat服务
celery -A proj beat -s /home/celery/var/run/celerybeat-schedule