[ celery定时任务 ]


django中celery使用定时任务

celery_app.py

import os

from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")

app = Celery("backend")

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object("django.conf:settings", namespace="CELERY")

# Load task modules from all registered Django app configs.自动扫描每个app里面的tasks.py文件
app.autodiscover_tasks()

某个app里面的tasks.py

from config import celery_app
from celery.schedules import crontab

schedule = {
    # 'email-to-deport': { ### to be confirmed
    #     'task': 'backend.cews.tasks.email2Depot',
    #     'schedule': crontab(hour=9, minute=0),
    # },
   'email-to-order-owner': { 
        'task': 'backend.cews.tasks.send_email_when_repair_order_non_active',
        'schedule': crontab(hour=9, minute=0),
    },
    'email-to-ntr-update-log': {
        'task': 'backend.cews.tasks.update_log_send_email',
        'schedule': crontab(hour=17, minute=00),
    }
    # 'sharepoint-update-stock-sw-version': { 
    #     'task': 'backend.cews.tasks.share_point_update_stock_sw_version',
    #     'schedule': crontab(hour=5, minute=0),
    # },
    }

celery_app.conf.beat_schedule = schedule