溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Django實現(xiàn)celery定時任務的方法

發(fā)布時間:2020-08-01 13:45:53 來源:億速云 閱讀:471 作者:小豬 欄目:開發(fā)技術(shù)

這篇文章主要講解了Django實現(xiàn)celery定時任務的方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。

1.首先在項目同名目錄下建一個celery.py

from __future__ import absolute_import
import os
from celery import Celery
from datetime import timedelta
from 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 settings

app = Celery('OpsManage')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
# 配置celery
class 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)
# 到各個APP里自動發(fā)現(xiàn)tasks.py文件
app.autodiscover_tasks()
#crontab config
app.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點
      # 'schedule': crontab(minute=0, hour=0)
    },
  },
)
# kombu : Celery 自帶的用來收發(fā)消息的庫, 提供了符合 Python 語言習慣的, 使用 AMQP 協(xié)議的高級接口
Queue('transient', routing_key='transient',delivery_mode=1)

2.在settings.py里配置celery

INSTALLED_APPS = [
  ......
  'django_celery_beat',
  'django_celery_results',
]

3.在項目同名目錄下的__init__.py文件里申明celery任務,記得要去檢測呀

# coding:utf-8
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']

import pymysql
pymysql.install_as_MySQLdb()

4.在task.py里執(zhí)行任務的函數(shù)上加@

from celery import task
# 定時任務
@task
def push_host_by_salt_tasks():
  “”“balabala”“”
  return '這里是定時任務'

看完上述內(nèi)容,是不是對Django實現(xiàn)celery定時任務的方法有進一步的了解,如果還想學習更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI