celery的使用
# 1 异步任务框架,执行异步任务,执行延迟任务,执行定时任务
# 2 Celery is a project with minimal funding, so we don’t support Microsoft Windows. Please don’t open any issues related to that platform.
pip install celery
9.1 基本结构
# 只写一个py文件 celery_task
from celery import Celery
broker='redis://127.0.0.1:6379/1' #broker任务队列
backend='redis://127.0.0.1:6379/2' # 结构存储,执行完的结果存在这
app=Celery(__name__,broker=broker,backend=backend)
@app.task
def add(x,y):
print(x,y)
return x+y
# 启动worker
# 非windows
celery worker -A celery_task -l info
# windows:
# pip3 install eventlet
celery worker -A celery_task -l info -P eventlet
# 添加任务
from celery_task import add
add(3,4) # 直接执行,不会被添加到broker中
ret=add.delay(5,4) #想broker中添加一个任务
# 查看任务执行结果
from celery_task import app
from celery.result import AsyncResult
id = '3e397fd7-e0c1-4c5c-999c-2655a96793bb'
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('任务已经开始被执行')
9.2 包结构
# 新建一个包,celery_task
-celery_task
-__init__.py
-celery.py
-task1.py
-task2.py
# celery.py
from celery import Celery
broker='redis://127.0.0.1:6379/1' #broker任务队列
backend='redis://127.0.0.1:6379/2'# 结构存储,执行完的结果存在这
app=Celery(__name__,broker=broker,backend=backend,include=['celery_task.task1','celery_task.task2'])
# task.py
from .celery import app
@app.task
def add(x,y):
print(x,y)
return x+y
# 添加任务(异步任务,延迟任务)
from celery_task.task1 import add
from celery_task.task2 import mutile
# 提交异步
ret=add.delay(6,7)
# 提交延迟任务
from datetime import datetime, timedelta
# 需要utc时间
eta=datetime.utcnow() + timedelta(seconds=10)
ret=add.apply_async(args=(240, 50), eta=eta)
9.3 执行定时任务
#1 celery.py
from celery import Celery
broker='redis://127.0.0.1:6379/1' #broker任务队列
backend='redis://127.0.0.1:6379/2' # 结构存储,执行完的结果存在这
app=Celery(__name__,broker=broker,backend=backend,include=['celery_task.task1','celery_task.task2'])
# 执行定时任务
# 时区
app.conf.timezone = 'Asia/Shanghai'
# 是否使用UTC
app.conf.enable_utc = False
# 任务的定时配置
from datetime import timedelta
from celery.schedules import crontab
app.conf.beat_schedule = {
'add-task': {
'task': 'celery_task.task1.add',
# 'schedule': timedelta(seconds=3),
'schedule': crontab(hour=8, day_of_week=1), # 每周一早八点
'args': (300, 150),
}