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

yipeiwu_com7年前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设计】。

相关文章

windows系统中Python多版本与jupyter notebook使用虚拟环境的过程

windows系统中Python多版本与jupyter notebook使用虚拟环境的过程

本人电脑是windows系统,装了Python3.7版本,但目前tensorflow支持最新的python版本为3.6,遂想再安装Python3.6以跑tensorflow.   因为看...

Python创建xml文件示例

本文实例讲述了Python创建xml文件的方法。分享给大家供大家参考,具体如下: 这是一个使用ElementTree有关类库,生成xml文件的例子 # *-* coding=utf-...

在python中利用numpy求解多项式以及多项式拟合的方法

构建一个二阶多项式:x^2 - 4x + 3 多项式求解 >>> p = np.poly1d([1,-4,3]) #二阶多项式系数 >>> p...

Python中基本的日期时间处理的学习教程

Python中基本的日期时间处理的学习教程

Python程序能用很多方式处理日期和时间。转换日期格式是一个常见的例行琐事。Python有一个 time 和 calendar 模组可以帮忙。 什么是Tick? 时间间隔是以秒为单位的...

详解Python self 参数

1、概述 1.1 场景 我们在使用 Python 中的 方法 method 时,经常会看到 参数中带有 self,但是我们也没对这个参数进行赋值,那么这个参数到底是啥意思呢? 2、知识点...