django+celery定时任务

第一步创建celery应用:

# celery入口

from celery import Celery

# 为celery使用django配置文件进行设置
import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'zkjy_lims.settings'


# 创建celery客户端实例,并起别名
celery_app = Celery('ZKJY')

# 加载celery配置
# 要求括号内以celery_tasks开始
celery_app.config_from_object('celery_tasks.config')


# 自动注册异步任务
celery_app.autodiscover_tasks(['celery_tasks.record_log','celery_tasks.sms', 'celery_tasks.j_push', 'echarts_pic.echarts_main_task', 'celery_tasks.sm_to_app','celery_tasks.sign_report','celery_tasks.copy_order', 'celery_tasks.timed_task'])

第二步config文件配置:

from celery.schedules import crontab
from datetime import timedelta
# celery配置服务器
BROKER_URL = "redis://127.0.0.1/13"

TIME_ZONE = 'Asia/Shanghai'

CELERY_ENABLE_UTC = True
CELERY_TIMEZONE = TIME_ZONE
# 任务队列配置
CELERY_ACCEPT_CONTENT = ['application/json', ]
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = "redis://127.0.0.1/0"
# 定时任务导入路径,这个一定要写,否则加载不到定时任务
CELERY_IMPORTS = ("celery_tasks.timed_task.tasks",)
# 定时任务
CELERYBEAT_SCHEDULE = {
    'update-user-base-info': {
        'task': 'celery_tasks.timed_task.tasks.user_base_info',  # 任务名
        # 'schedule': crontab(minute="*/1"),  # 每2s执行一次该任务
        'schedule': timedelta(seconds=3),
        'args': ()
    }
}

第三步启动:

启动worker: celery -A celery_tasks.main worker -l info 

启动beat: celery -A celery_tasks.main beat -l info --logfile=celery_beat.log

后台启动worker: celery multi start -A celery_tasks.main worker -l info 

后台启动beat: 

#!/bin/sh
case $1 in  
   start) cd /opt/django-celery/ && celery -A celery_pro beat -l info >  out.file  2>&1  & ;;

 

你可能感兴趣的:(celery)