https://github.com/Coxhuang/django-celery.git
每隔3秒钟,把当前的时间写入数据库
Django (2.0.7) celery (3.1.23) django-celery (3.2.2) # 如果Django是2以上的版本,django-celery不能是低版本 django-crontab (0.7.1) django-redis (4.9.0)
├─app │ │ admin.py │ │ apps.py │ │ models.py │ │ tasks.py # 新增文件 │ │ tests.py │ │ views.py │ │ __init__.py │ ├─celery_pro │ │ celery.py # 新增文件 │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ └─templates
修改INSTALLED_APPS
INSTALLED_APPS = [ ... 'djcelery', 'app', ]
在末尾加上
import djcelery from celery.schedules import crontab djcelery.setup_loader() BROKER_URL = 'redis://127.0.0.1:6379/0' from datetime import timedelta CELERYBEAT_SCHEDULE = { 'celery_test': { 'task': 'app.tasks.test_celery', 'schedule': timedelta(seconds=3), # 每隔3秒执行一次 'args': (16, 16) }, }
修改时区
TIME_ZONE = 'Asia/Shanghai' # 修改为上海时间 USE_I18N = True USE_L10N = True USE_TZ = False
在app目录下新建tasks.py文件
from __future__ import absolute_import from celery import task from app import models import datetime @task def test_celery(x, y): models.CeleryModels.objects.create(time=datetime.datetime.now()) # 把当前时间写入数据库 print("参数相加结果:",x+y) return "我是测试函数"
在celery_pro目录下 ( settings.py同一目录 ) 新建celery.py文件
from __future__ import absolute_import import os from celery import Celery, platforms # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_pro.settings') # 修改成celery_pro项目名 from django.conf import settings # noqa app = Celery('celery_pro') # 修改成celery_pro项目名 platforms.C_FORCE_ROOT = True # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
3.4 models.py
from django.db import models class CeleryModels(models.Model): time = models.DateTimeField(auto_now_add=True)
数据库迁移
python manage.py makemigrations python manage.py migrate
进入django项目的根目录执行如下代码启动celery的worker(在manage.py同一目录下):
celery -A celery_pro worker -l info # celery_pro 项目名
同样在django项目的根目录下再打开一个命令行界面,执行如下代码(在manage.py同一目录下):
celery -A celery_pro beat -l info # celery_pro 项目名
https://blog.csdn.net/Coxhuang/article/details/86921407
pip3 install flower
启动
celery -A app名 flower
https://flower-docs-cn.readthedocs.io/zh/latest/install.html#id2
在Django settings.py中设置定时任务时,存在这样一个问题:定时任务1不想要了,把代码删掉,但是在启动beat时,定时任务1还是会执行,如何把他从任务列表中删除呢?
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句