1.安装好celery
2.在你的django项目下新建一包queue(包名可以随便启),下面是我的结构
3.context_init.py 这是初始化django 项目环境变量的,在celery启动时会调用,下面是代码:
from __future__ import absolute_import
from django.core.management import setup_environ
import sys,os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
try:
import settings # Assumed to be in the same directory.
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
project_directory = setup_environ(settings)
project_name = os.path.basename(project_directory)
os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % project_name
4.task.py 使用celery的主要代码都在这:
#coding:utf-8
from __future__ import absolute_import
from celery import Celery
try:
import context_init
except ImportError:
from queue import context_init
import settings
from test import *
BROKER = 'redis://127.0.0.1:6379/1'
celery = Celery('tasks', broker=BROKER)
@celery.task
def test():
result = 1 + 1
return result
@celery.task
def test2(a, b):
result = a + b
return result
5. 启动celery , celery.sh 脚本:
PROJECT_DIR="/var/project/test/queue"
kill -KILL `ps aux|grep celery|awk '{print $2}'`
cd $PROJECT_DIR
/usr/local/python27/bin/celery -A tasks worker -l info >> /var/project/test/task.log 2>&1 &
echo "celery start..."
6.调用方法:
test.delay()
...
test2.delay(1,2)
完。