Celery的基本使用

Celery

# celery.py
from celery import Celery

backend = "redis://127.0.0.1:6379/1"
broker = "redis://127.0.0.1:6379/2"

app = Celery(__name__, broker, backend)

# 添加任务到 backend
@app.task
def add(x, y)
	print(x, y)
    return x + y
# run.py

# 执行任务
from .test import add
from datetime import datetime, timedelta

# 立刻执行----异步执行 add() 函数
t1 = add.delay(3, 4)
print(t1.id)

# 延时任务
# utcnow():国际时间:2021-04-22 01:12:15.579929
# timedelta:0:00:10
eta=datetime.utcnow() + timedelta(seconds=10)
add.apply_async(args=(1,2), eta=eta)
# result.py
from .test import app
from celery.result import AsyncResult

# id 在执行任务时获取
id = ‘21325a40-9d32-44b5-a701-9a31cc3c74b5‘
if __name__ == ‘__main__‘:
    async = AsyncResult(id=id, app=app)
    if async.successful():
        result = async.get()
        print(result)
    elif async.failed():
        print(‘任务失败‘)
    elif async.status == ‘PENDING‘:
        print(‘任务等待中被执行‘)
    elif async.status == ‘RETRY‘:
        print(‘任务异常后正在重试‘)
    elif async.status == ‘STARTED‘:
        print(‘任务已经开始被执行‘)

Celery的基本使用

上一篇:canvas常用操作


下一篇:关于引擎搜索的技巧