這裡記錄下 django 利用celery 實現定時任務的方法

這裡首先注意下版本問題

由於celery 4.0開始已經不支持 windows平台了, 可以在官網看到,所以這裡不能用最新的celery

版本如下:

windows10

Anaconda3

python:3.5

Django: 1.10.5

celery: 3.1.25

django-celery:3.2.1

以上均可用PIP 安裝,指定版本號即可

工程結構如下:

--project
--project
--__init__.py
--setting.py
--celery.py
--url.py
--....
--App1
--tasks.py
--....
--APP2
--tasks.py
--....

celery文件代碼如下:

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the celery program.
os.environ.setdefault(DJANGO_SETTINGS_MODULE, project.settings)

app = Celery(project)

# Using a string here means the worker dont 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)

# Load task modules from all registered Django app configs.
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

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

__init__.py 文件代碼如下:

from __future__ import absolute_import, unicode_literals

# 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

__all__ = [celery_app]

settings.py 文件進行修改

BROKER_URL = django://localhost:8000//
CELERYBEAT_SCHEDULER = djcelery.schedulers.DatabaseScheduler
# Application definition

INSTALLED_APPS = [
django.contrib.admin,
django.contrib.auth,
django.contrib.contenttypes,
django.contrib.sessions,
django.contrib.messages,
django.contrib.staticfiles,
App1
kombu.transport.django,
djcelery,
]

tasks文件代碼如下

from __future__ import absolute_import, unicode_literals
from celery import shared_task

@shared_task
def hello_world():
with open("output.txt", "a") as f:
f.write("hello world")
f.write("
")
print("hello world")

同步資料庫並運行伺服器,打開admin管理界面,添加定時任務,建立新的任務

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

ovember 04, 2017 - 21:17:21

Django version 1.10.5, using settings project.settings

Starting development server at 127.0.0.1:8000/

Quit the server with CTRL-BREAK.

之後打開兩個windows terminal , 我打開的是anaconda 的terminal

其中一個轉到文件目錄 並輸入 python manage.py celery -A project worker -l info

這裡項目名和app名不一樣,上面是便於理解

第二個同上,並輸入 python manage.py celery beat

最後可以看到


推薦閱讀:
相关文章