-
目录设置
image.png - 创建实例
# __init__.py
from celery import Celery
# 创建实例
app = Celery('demo')
# 通过Celery实例加载配置模块
app.config_from_object('celery_app.celeryconfig')
一、任务模拟
# task1.py
import time
from celery_app import app
@app.task
def add(x, y):
time.sleep(3)
return x + y
# task2.py
import time
from celery_app import app
@app.task
def multiply(x, y):
time.sleep(5)
return x * y
- 配置celeryconfig
# celeryconfig.py
BROKER_URL= 'redis://localhost:6379/1'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/2'
CELERY_TIMEZONE = 'Asia/Shanghai'
# 导入指定的任务模块
CELERY_IMPORTS = (
'celery_app.task1',
'celery_app.task2',
)
- 启动worker(项目目录下)
celery worker -A celery_app -l INFO
image.png
-
运行app.py
image.png
二、定时任务
- 配置
# celeryconfig.py
from datetime import timedelta
from celery.schedules import crontab
# 配置定时任务
CELERYBEAT_SCHEDULE = {
'task1':{
'task':'celery_app.task1.add',
'schedule':timedelta(seconds=10),
'args':(2,8),
},
'task2':{
'task':'celery_app.task2.multiply',
'schedule':crontab(hour=16,minute=45),
'args':(2,8),
},
}
- 另起终端,启动beat
celery beat -A celery_app -l INFO
-
展示
image.png -
worker beat 同时启动
celery -B -A celery_app worker -l INFO
网友评论