django使用supervisor管理celery

supervisor配置文件如下:

[program:celery]
; Set full path to celery program if using virtualenv
command=bash celery.sh or python manage.py celery worker or...

directory=/home/ubuntu/python/waterwxapi/
user=root
numprocs=1
stdout_logfile=/var/log/supervisor/celery.log
stderr_logfile=/var/log/supervisor/celery_error.log
autostart=true
autorestart=true
startsecs=10

; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600

; When resorting to send SIGKILL to the program to terminate it
; send SIGKILL to its whole process group instead,
; taking care of its children as well.
killasgroup=true
; Set Celery priority higher than default (999)
; so, if rabbitmq is supervised, it will start first.
priority=1000

django配置

pip install django-celery  Celery  celery-with-redis

settings.py

在INSTALLED_APPS中加入app:

INSTALLED_APPS = (
  ...
  'djcelery',
}

import djcelery
djcelery.setup_loader()

BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']

在某个apps的目录下新建一个tasks.py
如果用户是非root用户,而supervisor是 ROOT 用户进行的,所以要在tasks.py中加上

from celery import Celery,platforms
platforms.C_FORCE_ROOT = True

tasks.py

#coding=utf-8
from celery import Celery,platforms
from config import bind_device
app = Celery('tasks', broker='redis://localhost:6379//')
platforms.C_FORCE_ROOT = True
@app.task
def sendMesg(event):
  ...codes

sudo supervisorctl 重新restart项目

推荐阅读更多精彩内容