celery学习

1、安装 django-celery、celery、django-redis等一系列package

2、setting.py设置:

# celery参数配置
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml'] #接受传入参数类型
#CELERY_TASK_SERIALIZER = 'json'
#CELERY_RESULT_SERIALIZER = 'json'
CELERY_ENABLE_UTC = False
CELERYD_CONCURRENCY = 10
CELERYD_MAX_TASKS_PER_CHILD = 5
CELERY_SEND_EVENTS = True
# 定时任务
CELERYBEAT_SCHEDULE = {
'add-every-30-seconds': {
'task': 'trade.task.check_order_status',# 需要填入对应的任务名
'schedule': 60, #执行间隔时间
},
}
 

 celery.py设置:

from __future__ import absolute_import

import os
import django
from django.apps import apps, AppConfig

from celery import Celery
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()

app = Celery('backend')

app.config_from_object('django.conf:settings')
#app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])
installed_apps = [app_config.name for app_config in apps.get_app_configs()]
app.autodiscover_tasks(lambda: installed_apps, force=True)

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

   apps/app/task.py

from __future__ import absolute_import
from django.core.mail import send_mail

from celery import task, shared_task
from backend.settings import DEFAULT_FROM_EMAIL
# 导入redis模
@task
def send_email(vehicleorder):
  dosomething

同时需要在celery.py文件所在目录,在 __init__.py 中增加:否则celery无法找到task位置

from __future__ import absolute_import

# 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  # noqa

3、运行:

python manage.py runserver

再运行:

python manage.py celery worker --loglevel=info

4、注意点 :

1、virtualbox下ubuntu运行django-web项目,物理机访问虚拟机,需要在命令后面加上虚拟机IP和端口python manage.py runserver 192.168.2.249:8000,同时在setting.py内加上allowed_host 虚拟机IP.

2、makemigrations 需要删除 migrations/文件夹下的文件,删除对应的sql表,还要在database中的migrations表中删除记录,缺一不可

3、在celery 中添加 定时 task 后, 任务会储存到 djcelery-periodictask 表中 ,即使你在django中 删除了定时任务, 该任务也还会继续执行,需要在 sql表中删除。

原文地址:https://www.cnblogs.com/kkkboshow/p/9409448.html