Django Celery定时任务

Posted daidechong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django Celery定时任务相关的知识,希望对你有一定的参考价值。


安装
celery
redis
eventlet
django_celery_beat(安装后数据库迁移)

1.项目目录创建celery.py

# -*-coding:utf-8 -*-

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.utils import timezone

# set the default Django settings module for the ‘celery‘ program.
env = os.environ.get(ENV)
#
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")

app = Celery(celert-test)

# Using a string here means the worker doesn‘t have to serialize
# the configuration object to child processes.
# - namespace=‘CELERY‘ means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object(django.conf:settings, namespace=CELERY)

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()

2.项目目录__init__

from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = (celery_app,)

3.setting.py

# celery 配置
CELERY_BEAT_SCHEDULER = django_celery_beat.schedulers:DatabaseScheduler
CELERY_TIMEZONE = Asia/Shanghai ## 使用亚洲/上海时区
CELERY_IGNORE_RESULT = True
#设置存储Celery任务队列的Redis数据库
CELERY_BROKER_URL = redis://:pwd@host:prot/1 # Broker配置,使用Redis作为消息中间件
CELERY_ACCEPT_CONTENT = [json]
CELERY_TASK_SERALIZER = json
#设置存储Celery任务结果的数据库
CELERY_RESULT_BACKEND = redis://:pwd@host:prot/1 # BACKEND配置,这里使用redis
# CELERY_RESULT_BACKEND = ‘django-db‘
# 避免时区的问题
CELERY_ENABLE_UTC = False
DJANGO_CELERY_BEAT_TZ_AWARE = False

4.Xadmin.py

from django_celery_beat.models import IntervalSchedule, CrontabSchedule, PeriodicTask

class PeriodicTaskAdmin(object):
list_display = [
name, task, args, kwargs, queue,
exchange, routing_key, expires, enabled,
last_run_at, total_run_count, date_changed, description,
interval, crontab, solar, clocked, one_off,
start_time, priority, headers
]
ordering = [id]
search_fields = [name]
list_per_page = 10


class IntervalScheduleAdmin(object):
ordering = [id]
list_per_page = 10


class CrontabScheduleAdmin(object):
list_display = [
id,
minute,
hour,
day_of_week,
day_of_month,
month_of_year,
timezone
]
ordering = [id]
search_fields = [minute]
list_per_page = 10

#定时
xadmin.site.register(CrontabSchedule, CrontabScheduleAdmin)
xadmin.site.register(IntervalSchedule, IntervalScheduleAdmin)
xadmin.site.register(PeriodicTask, PeriodicTaskAdmin)

5.在Xadmin中设置定时任务

  设置IntervalSchedule或者CrontabSchedule
  PeriodicTask中添加定时
6.在Django启动的前提下,在项目目录路径下打开两个Terminl分别运行下面命令

启动Celery
celery -A main worker -l info -P eventlet
启动定时任务
celery -A main beat -l info -S django

 

 

 

以上是关于Django Celery定时任务的主要内容,如果未能解决你的问题,请参考以下文章

Celery+python+redis异步执行定时任务

django+celery配置(定时任务)

Django Celery定时任务

python测试开发django-197.django-celery-beat 定时任务

django —— Celery实现异步和定时任务

在django中使用celery异步任务和定时任务