How to write a celery regular tasks Django-

1. First, build a project of the same name in the directory 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 / of Shanghai ' CELERY_ENABLE_UTC = True CELERY_ANNOTATIONS = { ' * ' : { ' rate_limit ' : ' 500 / S ' }} CELERYBEAT_SCHEDULER = ' djcelery.schedulers.DatabaseScheduler ' app.config_from_object (Config) # to the APP in the respective automatic found tasks.py file app.autodiscover_tasks () # the crontab config app.conf.update ( CELERYBEAT_SCHEDULE = { # every function is performed once 30s ' Every-30-min-the Add ' : { ' Task ' : ' apps.tasks.celery_assets.push_host_by_salt_tasks ' , ' Schedule ' : timedelta (= 30 seconds The ) # # daily 12:00 # 'Schedule': the crontab (= minute 0, = 0 hour) }, }, ) # kombu: Celery own library to send and receive messages, is provided in line with Python language habits, use of high-level interface protocol AMQP Queue ( ' transient ' , routing_key = ' transient ' , delivery_mode = 1)

2. Configure celery in the settings.py

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

3. Affirms celery task __init__.py file in the project directory of the same name, remember going to detect it

# 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. Perform the tasks function in task.py Riga @

from Celery Import Task 

# timer task 
@task
 DEF push_host_by_salt_tasks (): 
    "" "balabala" "" 
    return  ' here is a timing task '

Guess you like

Origin www.cnblogs.com/lutt/p/12037661.html