无法使用Celery + Django + Gunicorn运行后台任务

时间:2019-07-05 12:56:16

标签: python django nginx celery gunicorn

堆栈:

Python v2.7
Django v1.11
Celery v4.3.0
Gunicorn v19.7.1
Nginx v1.10
  

当我尝试手动运行django服务器和celery时,异步任务将按预期执行。

     
     

当我使用django加上Gunicorn部署Nginx项目时,问题就来了。   我尝试使用Celery运行supervisor,但没有帮助。


views.py

def _functionA():
    _functionB.delay() #where _functionB is registered async task.

settings.py

# Celery settings
CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'

celery_init.py

from __future__ import absolute_import
import os

from celery import Celery


# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cpi_server.settings')

app = Celery('myproject')

# 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()

__init__.py



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

__all__ = ['celery_app']

gunicorn.service

[Unit]
Description=Gunicorn application server....
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=<myprojectdir>
Environment=PYTHONPATH=<ENV>
ExecStart=<myprojectdir>/env/bin/gunicorn --workers 3 --access-logfile access_gunicorn.log --error-logfile error_gunicorn.log --capture-output --log-level debug --bind unix:<myprojectdir>/myproject.sock <myproject>.wsgi:application

[Install]
WantedBy=multi-user.target

myproject_nginx.conf

server {
    listen 8001;
    location / {
        include proxy_params;
        proxy_pass http://unix:<myprojectdir>/myproject.sock;
    }
}

celery worker

celery worker -B -l info -A myproject -Q celery,queue1,queue2,queue3 -n beat.%h -c 1

有人可以帮我解决以下问题吗?

  

为什么当使用Gunicorn和nginx部署Django时,Celery工人不执行任务,而手动运行时它可以执行任务,即使用python manage.py runserver ...运行时。

1 个答案:

答案 0 :(得分:1)

您的并发级别等于1(辅助程序命令行中的-c 1)。基本上,这意味着该工作程序被配置为在任何时间运行一次“单项任务”。如果您的任务是长时间运行的,那么您可能会觉得Celery没有运行任何东西...

您可以轻松地对此进行测试-当您开始执行某些任务时,请运行以下命令:

celery -A myproject inspect active

这将列出您正在运行的任务(如果有)。

要解决的另一件事是您的配置变量。 Celery 4现在期望所有配置变量均为小写。阅读What’s new in Celery 4.0 (latentcall)文档以了解更多信息,尤其是Lowercase setting names部分。