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

作者:BigYoung 时间:2023-03-21 06:19:07 

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 test
django-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_literals
import os
from 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 here
from __future__ import absolute_import, unicode_literals
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)

第三步:任务执行

运行django项目: python manage.py runserver

3.1 后台添加计划任务

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

3.2 启动定时的celery服务

注意:celery依赖redis服务,需要提前运行redis服务:`redis-server`


# 以下两个命令在不同的shell窗口里执行,需要在django的目录下
python manager.py celery beat -l info  #接收定时任务的命令
python manager.py celery worker -l info #执行定时任务的命令,此shell窗口会看到任务的输入信息

3.3 启动单次的celery服务

注意:celery依赖redis服务,需要提前运行redis服务:`redis-server`


python manager.py shell  # 进到django的shell里
from demo.task import mul, xsum  # 导入task任务
a = mul()
b = xsum()
# 执行a, b会输出信息
a(1,2)
b(1)

PS:django-crontab实现Django定时任务

django-crontab安装:


pip install django-crontab

django-crontab加入:只需要将django-crontab加入到settings.py的INSTALLED_APPS即可。如下代码:


INSTALLED_APPS = (

'django_crontab',

...

)

django-crontab配置:settings.py中加入django-crontab的命令即可:


CRONJOBS = [

('47 11 * * *', 'django.core.management.call_command', ['closepoll'],{},'>> /var/run.log'),

]

格式:

参数1:定时 例如47 11 * * * 表示每天的11时47分执行
参数2:方法的python模块路径,如果执行django-admin命令,则写django.core.management.call_command
参数3:方法的位置参数列表(默认值:[]),如果执行django-admin命令,则填写所需执行的命令,例如我们在polls中已经定义过的closepoll
参数4:方法的关键字参数的dict(默认值:{})
参数5:执行log存放位置(即重定向到文件,默认:'')

django-crontab任务加载:

django-crontab任务加载比较简单,只需要运行 python manage.py crontab add 即可

查看已经激活的任务使用 python manage.py crontab show

删除已经有的任务使用 python manage.py crontab remove

如果你修改了任务记得一定要使用 python manage.py crontab add 这个会更新定时任务

来源:http://www.bigyoung.cn/1096.html

标签:Django,定时任务
0
投稿

猜你喜欢

  • MYSQL拒绝访问报错not allowed to connect

    2024-01-16 02:20:21
  • 浅谈JavaScript 中的延迟加载属性模式

    2024-04-17 10:29:56
  • SQL查询之字段是逗号分隔开的数组如何查询匹配数据问题

    2024-01-21 22:32:08
  • 微软的jQuery国际化插件

    2010-07-02 12:46:00
  • sqlserver CONVERT()函数用法小结

    2024-01-19 05:14:17
  • 如何利用SysOjects来获知数据库的信息?

    2010-01-01 15:43:00
  • 使用uni-app开发微信小程序的实现

    2024-05-13 09:10:42
  • python调用staf自动化框架的方法

    2021-11-03 17:47:43
  • python 匹配url中是否存在IP地址的方法

    2023-04-13 14:29:08
  • Python实现的朴素贝叶斯算法经典示例【测试可用】

    2021-09-10 19:15:25
  • 原生js实现查找/添加/删除/指定元素的class

    2024-04-18 09:44:46
  • asp 页面允许CACHE的方法

    2011-02-16 11:20:00
  • Django 解决开发自定义抛出异常的问题

    2023-03-05 12:43:55
  • 网页上的广告条设计思考

    2008-06-29 14:16:00
  • Python中基本数据类型和常用语法归纳分享

    2023-09-08 21:08:01
  • 使用Django的模版来配合字符串翻译工作

    2023-11-17 06:03:47
  • js中var、let、const之间的区别

    2024-04-23 09:11:29
  • MySQL5.7.18主从复制搭建(一主一从)教程详解

    2024-01-25 12:55:03
  • PHP实时统计中文字数和区别

    2023-07-13 10:44:01
  • Firefox 3.5 新增加的支持(整理)

    2009-08-01 12:51:00
  • asp之家 网络编程 m.aspxhome.com