Python Django2.0集成Celery4.1教程
環(huá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文件中添加如下內容
... 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 # 設置環(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任務 @task def print_hello(): return 'hello celery and django...'
配置周期性任務或定時任務
再次編輯settings.py文件,添加如下內容
定時任務的配置格式參考:http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html
from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { # 周期性任務 'task-one': { 'task': 'app.tasks.print_hello', 'schedule': 5.0, # 每5秒執(zhí)行一次 # 'args': () }, # 定時任務 'task-two': { 'task': 'app.tasks.print_hello', 'schedule': crontab(minute=0, hour='*/3,10-19'), # 'args': () } }
啟動worker和定時任務
啟動worker (切換到manage.py同級目錄下執(zhí)行)
celery -A project_name worker -l info -P eventlet
啟動定時任務或周期性任務
celery -A project_name beat -l info
這里備注一下:最好使用supervisord來管理上面這2條命令
存放任務結果的擴展
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ù)庫存放任務執(zhí)行結果信息)
以上這篇Python Django2.0集成Celery4.1教程就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
node命令行服務器(http-server)和跨域的實現(xiàn)
本文主要介紹了node命令行服務器(http-server)和跨域的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02Python中Numpy與TensorFlow版本兼容問題完美解決辦法
這篇文章主要給大家介紹了關于Python中Numpy與TensorFlow版本兼容問題的完美解決辦法,確保Python版本與TensorFlow版本兼容是首要任務,因為不兼容的組合可能導致導入錯誤或其他運行時問題,需要的朋友可以參考下2024-07-07python3報錯check_hostname?requires?server_hostname的解決
這篇文章主要介紹了python3報錯check_hostname?requires?server_hostname的解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12