celery中share_task的使用详解

代码

s1.py

import requests

@shared_task
def refresh_all():
    r = requests.post('http://127.0.0.1:7800/')
    print(r)

from celery import Celery
app = Celery('tasks', broker='redis://192.168.10.48:6379', backend='redis://192.168.10.48:6379')

s2.py

# 立即告诉celery去创建并执行x1任务,并传两个参数
from s1 import refresh_all
result = refresh_all.delay()
print(result.id)	# 任务ID

s3.py

from celery.result import AsyncResult
from s1 import app
# id 参数需要改
result_object = AsyncResult(id="17c7f019-36a5-40da-ac4c-99f7c26f518c", app=app)
print(result_object.status)	# 任务状态

data = result_object.get()	# 获取任务结果
print(data)

执行步骤

1、启动redis

2、启动worker

# 首先要进入当前目录
celery worker -A s1 -l info
# -A s1	找到项目
# -l info	是打印日志log,代码上线时不加info

3、创建任务,放入broker

python s2.py

4、查看任务状态

# 在s3.py填写任务ID
ptyhon s3.py

你可能感兴趣的:(python,后端,python,celery,share_task)