一、基本使用
django_celery_demo ├── app01 │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── models.py │ ├── tasks.py │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── django_celery_demo │ ├── __init__.py │ ├── celery.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── red.py └── templates
import os from celery import Celery # set the default Django settings module for the ‘celery‘ program. os.environ.setdefault(‘DJANGO_SETTINGS_MODULE‘, ‘django_celery_demo.settings‘) app = Celery(‘django_celery_demo‘) # 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.autodiscover_tasks()
django_celery_demo/celery.py
from .celery import app as celery_app __all__ = (‘celery_app‘,)
django_celery_demo/__init__.py
from celery import shared_task @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y @shared_task def xsum(numbers): return sum(numbers)
app01/tasks.py
# ######################## Celery配置 ######################## CELERY_BROKER_URL = ‘redis://10.211.55.20:6379‘ CELERY_ACCEPT_CONTENT = [‘json‘] CELERY_RESULT_BACKEND = ‘redis://10.211.55.20:6379‘ CELERY_TASK_SERIALIZER = ‘json‘
django_celery_demo/settings.py
from django.shortcuts import render, HttpResponse from app01 import tasks from django_celery_demo import celery_app from celery.result import AsyncResult def index(request): result = tasks.add.delay(1, 8) print(result) return HttpResponse(‘...‘) def check(request): task_id = request.GET.get(‘task‘) async = AsyncResult(id=task_id, app=celery_app) if async.successful(): data = async.get() print(‘成功‘, data) else: print(‘任务等待中被执行‘) return HttpResponse(‘...‘)
app01/views.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^index/‘, views.index), url(r‘^check/‘, views.check), ]
django_celery_demo/urls.py
定时任务 就是在view里面用
def index(request): # result = tasks.add.delay(1, 8) ctime = datetime.datetime.now() utc_ctime = datetime.datetime.utcfromtimestamp(ctime.timestamp()) s10 = datetime.timedelta(seconds=10) ctime_x = utc_ctime + s10 # 使用apply_async并设定时间 result = tasks.add.apply_async(args=[1, 3], eta=ctime_x) print(result) return HttpResponse(‘...‘)
参考https://www.cnblogs.com/wupeiqi/articles/8796552.html
原文地址:https://www.cnblogs.com/a438842265/p/12510906.html
时间: 2024-11-13 04:33:12