Django實(shí)現(xiàn)celery定時(shí)任務(wù)過(guò)程解析
1.首先在項(xiàng)目同名目錄下建一個(gè)celery.py
from __future__ import absolute_importimport osfrom celery import Celeryfrom datetime import timedeltafrom kombu import Queue# set the default Django settings module for the ’celery’ program.os.environ.setdefault(’DJANGO_SETTINGS_MODULE’, ’OpsManage.settings’)from django.conf import settingsapp = Celery(’OpsManage’)# Using a string here means the worker will not have to# pickle the object when using Windows.# 配置celeryclass Config: BROKER_URL = ’amqp://guest:guest@localhost:5672//’ CELERY_RESULT_BACKEND = ’redis://localhost:6379’ CELERY_ACCEPT_CONTENT = [’application/json’] CELERY_TASK_SERIALIZER = ’json’ CELERY_RESULT_SERIALIZER = ’json’ CELERY_TASK_RESULT_EXPIRES = 60 * 60 CELERY_TIMEZONE = ’Asia/Shanghai’ CELERY_ENABLE_UTC = True CELERY_ANNOTATIONS = {’*’: {’rate_limit’: ’500/s’}} CELERYBEAT_SCHEDULER = ’djcelery.schedulers.DatabaseScheduler’app.config_from_object(Config)# 到各個(gè)APP里自動(dòng)發(fā)現(xiàn)tasks.py文件app.autodiscover_tasks()#crontab configapp.conf.update( CELERYBEAT_SCHEDULE = { # 每隔30s執(zhí)行一次函數(shù) ’every-30-min-add’: { ’task’: ’apps.tasks.celery_assets.push_host_by_salt_tasks’, ’schedule’: timedelta(seconds=30) # # 每天凌晨12點(diǎn) # ’schedule’: crontab(minute=0, hour=0) }, },)# kombu : Celery 自帶的用來(lái)收發(fā)消息的庫(kù), 提供了符合 Python 語(yǔ)言習(xí)慣的, 使用 AMQP 協(xié)議的高級(jí)接口Queue(’transient’, routing_key=’transient’,delivery_mode=1)
2.在settings.py里配置celery
INSTALLED_APPS = [ ...... ’django_celery_beat’, ’django_celery_results’,]
3.在項(xiàng)目同名目錄下的__init__.py文件里申明celery任務(wù),記得要去檢測(cè)呀
# coding:utf-8from __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’]import pymysqlpymysql.install_as_MySQLdb()
4.在task.py里執(zhí)行任務(wù)的函數(shù)上加@
from celery import task# 定時(shí)任務(wù)@taskdef push_host_by_salt_tasks(): “”“balabala”“” return ’這里是定時(shí)任務(wù)’
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式2. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))3. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)4. XML入門(mén)的常見(jiàn)問(wèn)題(四)5. HTML5 Canvas繪制圖形從入門(mén)到精通6. XML入門(mén)的常見(jiàn)問(wèn)題(一)7. JavaWeb Servlet中url-pattern的使用8. 微信開(kāi)發(fā) 網(wǎng)頁(yè)授權(quán)獲取用戶基本信息9. XML解析錯(cuò)誤:未組織好 的解決辦法10. asp批量添加修改刪除操作示例代碼
