首页 > 编程 > Python > 正文

如何在Django中设置定时任务的方法示例

2020-02-16 00:43:55
字体:
来源:转载
供稿:网友

Django 作为后端Web开发框架,有时候我们需要用到定时任务来或者固定频次的任务来执行某段代码,这时我们就要用到Celery了。Django中有一个中间件:Django-celery

环境:

Python 3.6 Django为小于1.8版本 Celery为3.1版本

第一步安装:django-celery

pip install django-celery

第二步:配置celery和任务

创建测试django环境:

django-admin.py createproject testdjango-admin.py startapp demo

创建好的项目布局如下:

- proj/ - manage.py - proj/  - __init__.py  - celery.py  - settings.py  - urls.py - demo/  - migrations  - __init__.py  - admin.py  - apps.py  - models.py  - tasks.py  - tests.py  - views.py

2.1 配置celery.py文件

需要替换的内容,我都在对应的行后提示了,剩下的内容默认就好

创建test/test/celery.py文件,内容如下:

from __future__ import absolute_import, unicode_literalsimport osfrom celery import Celery # set the default Django settings module for the 'celery' program.os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')  # “proj.settings”替换为你的项目信息:test.settings app = Celery('proj') # 这里的proj替换为你的项目名称:test # 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()  @app.task(bind=True)def debug_task(self):  print('Request: {0!r}'.format(self.request))

2.2 配置项目的init.py中配置celery内容

打开test/test/__init_.py文件,添加内容:

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',)

2.3 在task.py中添加计划任务

编辑test/demo/task.py文件,添加计划任务,内容如下:

# Create your tasks herefrom __future__ import absolute_import, unicode_literalsfrom celery import shared_task  @shared_taskdef add(x, y):  return x + y  @shared_taskdef mul(x, y):  return x * y  @shared_taskdef xsum(numbers):  return sum(numbers)

第三步:任务执行

运行django项目: python manage.py runserver

3.1 后台添加计划任务

访问“http://localhost:8000/admin/”,在celery的管理页面里,选择Periodic tasks,进行任务添加。选择对应的任务,设置定时或者周期时间

3.2 启动定时的celery服务

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表