Celery 简单搭建运行

新建项目名为 proj

  • proj
    • __init__.py
    • app.py
    • tasks.py

app.py

from celery import Celery
from kombu import Exchange, Queue

app = Celery('proj',
             broker='amqp://admin:[email protected]:5672',
             backend='redis://127.0.0.1:6379/1',
             task_serializer = 'json',
             result_serializer = 'json',
             accept_content = ['json'],
             timezone = 'Europe/Oslo',
             enable_utc = True,
             include=['proj.tasks'],
             )
app.conf.update(
    task_queues=[
        Queue('littleCar_instructions', Exchange('littleCar'),                     
        routing_key='little_routingKey',
        #queue_arguments={'x-max-length': 3}),
    ],

)

if __name__ == '__main__':
    app.start()

broker 消息中间件, worker从worker中获取消息来执行task

backend 任务执行结果存储 

tasks.py

from proj.app import app
import time
@app.task()
def getmsg(msg):
    print("开始执行任务")
    return msg

这是celery流程图

Celery_framework

打开cmd 执行命令:

celery -A proj.app worker -l info

运行日志 [queues] 是worker监听的队列

[tasks] 是绑定worker绑定的任务

worker启动后来生产消息,让worker来执行任务

可以写个py 也可以直接往队列发送消息

main.py

from dipan.proj.tasks import getmsg

# r1=mul.apply_async((), queue='test', countdown=10)
r1=getmsg.delay(1)
print(r1)

猜你喜欢

转载自blog.csdn.net/wuhchengfei616/article/details/105067668