django+celery配置(定時任務+循環任務)

下面介紹一下django+celery的配置作定時任務python

1.首先介紹一下環境和版本redis

   python==2.7數據庫

 django == 1.8.1django

   celery == 3.1.23session

   django-celery == 3.1.17app

2.celery的安裝測試

  sudo pip install celery==3.1.23spa

  sudo pip install django-celery==3.1.17debug

3.新建一個項目code

  (1)django-admin startproject django_celery_demo

      (2)cd django_celery_demo

      (3)django-admin startapp appdemo

4.修改項目配置(django_celery_demo/django_celery_demo/settings.py)

    (1)第一行引入absolute_import

from __future__ import absolute_import

    (2)INSTALLED_APPS添加'djcelery','appdemo'

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'djcelery',
    'appdemo',
)

    (3)在setting.py最下方加入

import djcelery
from celery.schedules import crontab
djcelery.setup_loader()
BROKER_URL = 'redis://:dahai123@192.168.5.60:6380/6'
# BROKER_URL = 'redis://:密碼@主機地址:端口號/數據庫號'

from datetime import timedelta


CELERYBEAT_SCHEDULE = {
    'add-every-3-seconds': {
        'task': 'appdemo.tasks.test_celery',
        # 'schedule': crontab(minute=u'40', hour=u'17',),
        'schedule': timedelta(seconds=3),
        'args': (16, 16)
    },
}

5.建立django_celery_demo/django_celery_demo/celery.py,文件內容以下

from __future__ import absolute_import

import os

from celery import Celery, platforms

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

from django.conf import settings  # noqa

app = Celery('django_celery_demo')
platforms.C_FORCE_ROOT = True

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)


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

 

6.在django_celery_demo/django_celery_demo/__init__.py引入

from __future__ import absolute_import
from .celery import app as celery_app

7.建立django_celery_demo/appdemo/tasks.py文件,內容以下

 

from __future__ import absolute_import

import logging
from celery import task
from celery.utils.log import get_task_logger
from celery.schedules import crontab


@task
def test_celery(x, y):
    logger = get_task_logger(__name__)
    logger.info('func start  ----------------->')
    logger.info('application:%s', "TEST_APP")
    logger.info('func end -------------------->')
    print x + y
    return x + y


@task
def test_multiply(x, y):
    logger = get_task_logger(__name__)
    logger.info('func start  ----------------->')
    logger.info('application:%s', "TEST_APP")
    logger.info('func end -------------------->')
    print x * y
    return x * y

 

 

 

8.開始測試

  python manage.py makemigrations  # 同步數據庫,首次使用

  python  manage.py celery -A django_celery_demo  worker -B    # django_celery_demo爲celery和setting所在文件夾名

  

9.上面時循環任務,還能夠作定時任務:

django_celery_demo/django_celery_demo/settings.py

CELERYBEAT_SCHEDULE = {
    'add-every-3-seconds': {
        'task': 'appdemo.tasks.test_celery',
        # 'schedule': crontab(minute=u'40', hour=u'17',),
        'schedule': timedelta(seconds=3),
        'args': (16, 17)
    },
    'timing': {
        'task': 'appdemo.tasks.test_multiply',
        'schedule': crontab(minute=u'28', hour=u'11',),
        # 'schedule': timedelta(seconds=3),
        'args': (2, 3)
    },
}

不要忘了把時間改成北京時間,我在上海就改爲了上海

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

定時在11:28開啓的任務執行

相關文章
相關標籤/搜索