Python Django2.0集成Celery4.1教程
環(huán)境準(zhǔn)備
Python3.6
pip install Django==2.0.1
pip install celery==4.1.0
pip install eventlet (加入?yún)f(xié)程支持)
安裝erlang和rabbitMQ-server
配置settings.py文件
在settings.py文件中添加如下內(nèi)容
... LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = False CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672'
在settings.py同級目錄創(chuàng)建celery.py
celery.py
注意替換: project_name
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# 設(shè)置環(huán)境變量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings')
# 注冊Celery的APP
app = Celery('project_name')
# 綁定配置文件
app.config_from_object('django.conf:settings', namespace='CELERY')
# 自動發(fā)現(xiàn)各個app下的tasks.py文件
app.autodiscover_tasks()
修改settings.py同級目錄的init.py文件
from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app']
在某個APP中創(chuàng)建tasks.py文件
tasks.py
# -*- coding: utf-8 -*- from celery.task import task # 自定義要執(zhí)行的task任務(wù) @task def print_hello(): return 'hello celery and django...'
配置周期性任務(wù)或定時任務(wù)
再次編輯settings.py文件,添加如下內(nèi)容
定時任務(wù)的配置格式參考:http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html
from celery.schedules import crontab
CELERY_BEAT_SCHEDULE = {
# 周期性任務(wù)
'task-one': {
'task': 'app.tasks.print_hello',
'schedule': 5.0, # 每5秒執(zhí)行一次
# 'args': ()
},
# 定時任務(wù)
'task-two': {
'task': 'app.tasks.print_hello',
'schedule': crontab(minute=0, hour='*/3,10-19'),
# 'args': ()
}
}
啟動worker和定時任務(wù)
啟動worker (切換到manage.py同級目錄下執(zhí)行)
celery -A project_name worker -l info -P eventlet
啟動定時任務(wù)或周期性任務(wù)
celery -A project_name beat -l info
這里備注一下:最好使用supervisord來管理上面這2條命令
存放任務(wù)結(jié)果的擴(kuò)展
pip install django-celery-results Install APP INSTALLED_APPS = ( ..., 'django_celery_results', )
生成數(shù)據(jù)庫表:python manage.py migrate django_celery_results
配置settings:CELERY_RESULT_BACKEND = 'django-db' (用數(shù)據(jù)庫存放任務(wù)執(zhí)行結(jié)果信息)
以上這篇Python Django2.0集成Celery4.1教程就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
node命令行服務(wù)器(http-server)和跨域的實現(xiàn)
本文主要介紹了node命令行服務(wù)器(http-server)和跨域的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Python中Numpy與TensorFlow版本兼容問題完美解決辦法
這篇文章主要給大家介紹了關(guān)于Python中Numpy與TensorFlow版本兼容問題的完美解決辦法,確保Python版本與TensorFlow版本兼容是首要任務(wù),因為不兼容的組合可能導(dǎo)致導(dǎo)入錯誤或其他運行時問題,需要的朋友可以參考下2024-07-07
實例講解Python的函數(shù)閉包使用中應(yīng)注意的問題
這里我們來以實例講解Python的函數(shù)閉包使用中應(yīng)注意的問題,主要針對閉包后新生成的變量來不及初始化而導(dǎo)致找不到變量的錯誤出現(xiàn),需要的朋友可以參考下2016-06-06
python3報錯check_hostname?requires?server_hostname的解決
這篇文章主要介紹了python3報錯check_hostname?requires?server_hostname的解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12

