celery实现异步任务、定时任务和延迟任务

1.异步任务

任务名.delay(传参数)   

2.延迟任务

from datetime import datetime, timedelta

# atetime.utcnow() 当前utc时间
# 当前时间+15秒
eta = datetime.utcnow() + timedelta(seconds=15)
# 取消订单任务
res = cancel_order.apply_async(args=['10001',], eta=eta)  # 15s 后执行这个任务
print(res)

3 定时任务 —— 需要启动beat

3.1 在celery.py 中配置

# 时区
app.conf.timezone = 'Asia/Shanghai'
# 是否使用UTC
app.conf.enable_utc = False
# 任务的定时配置
from datetime import timedelta
from celery.schedules import crontab

app.conf.beat_schedule = {
    'send_sms': {
        'task': 'celery_task.user_task.send_sms',
        'schedule': timedelta(seconds=3),  # 每隔3s执行一次
        # 'schedule': crontab(hour=8, day_of_week=1),  # 每周一早八点
        'args': ('1896388888', '6666'),
    }
}

3.2 启动worker

celery -A celery_task worker -l info -P eventlet

3.3 启动beat

celery -A celery_task beat -l info
posted @ 2024-01-29 19:15  wellplayed  阅读(118)  评论(0编辑  收藏  举报