django使用django-apscheduler 实现定时任务的例子

yipeiwu_com6年前Python基础

下载:

pip install apscheduler

pip install django-apscheduler

将 django-apscheduler 加到项目中settings的INSTALLED_APPS中

INSTALLED_APPS = [

  ....

  'django_apscheduler',

]

然后迁移文件后

./manage.py migrate

生成两个表:django_apscheduler_djangojob 和 django_apscheduler_djangojobexecution

这两个表用来管理你所需要的定时任务,然后就开始在任一view下写你需要实现的任务:

启动异步定时任务
 import time
 from apscheduler.schedulers.background import BackgroundScheduler
 from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
 try: 
    # 实例化调度器
    scheduler = BackgroundScheduler()
    # 调度器使用DjangoJobStore()
    scheduler.add_jobstore(DjangoJobStore(), "default")
    # 'cron'方式循环,周一到周五,每天9:30:10执行,id为工作ID作为标记
    # ('scheduler',"interval", seconds=1) #用interval方式循环,每一秒执行一次
    @register_job(scheduler, 'cron', day_of_week='mon-fri', hour='9', minute='30', second='10',id='task_time')
    def test_job():
      t_now = time.localtime()
      print(t_now)
 
   # 监控任务
   register_events(scheduler)
   # 调度器开始
   scheduler.start()
except Exception as e:
  print(e)
  # 报错则调度器停止执行
  scheduler.shutdown()

以上这篇django使用django-apscheduler 实现定时任务的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中的逆序遍历实例

如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列。 range()语法: range(start,end,step=1):顾头不顾尾 正序遍历: range(10):...

浅谈python脚本设置运行参数的方法

浅谈python脚本设置运行参数的方法

正在学习Django框架,在运行manage.py的时候需要给它设置要监听的端口,就是给这个脚本一个运行参数。教学视频中,是在Eclipse中设置的运行参数,网上Django大部分都是在...

python实现sublime3的less编译插件示例

利用http://tool.oschina.net/less 提供的接口,发送请求进行远程编译.再将编译好的less,保存为同名后缀为css的文件中.第一次使用python,代码也是拼拼...

python对象及面向对象技术详解

本文实例讲述了python对象及面向对象技术。分享给大家供大家参考,具体如下: 1 先看一个例子. 本章将讲解这个例子程序: 文件: fileinfo.py: """Framewor...

python+matplotlib实现鼠标移动三角形高亮及索引显示

python+matplotlib实现鼠标移动三角形高亮及索引显示

Trifinder事件实例 实例展示Trifinder对象对的使用。当鼠标移动到一个被分割的三角形上,这个三角形高亮显示,并且它的标签在图标题显示。 展示下演示结果: 完整代码:...