Celery 基本使用

2019-04-25  本文已影响0人  爱修仙的道友
# __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.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',
)
celery worker -A celery_app -l INFO
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),
    },
}
celery beat -A celery_app -l INFO
celery -B -A celery_app worker -l INFO
上一篇下一篇

猜你喜欢

热点阅读