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 装饰器深入理解

讲 Python 装饰器前,我想先举个例子,虽有点污,但跟装饰器这个话题很贴切。 每个人都有的内裤主要功能是用来遮羞,但是到了冬天它没法为我们防风御寒,咋办?我们想到的一个办法就是把内裤...

对dataframe进行列相加,行相加的实例

实例如下所示: >>> import pandas as pd >>> df = pd.DataFrame({"x":['a','b','c','...

python如何制作英文字典

本文实例为大家分享了python制作英文字典的具体代码,供大家参考,具体内容如下 功能有添加单词,多次添加单词的意思,查询,退出,建立单词文件。 keys=[] dic={} def...

简介Python的collections模块中defaultdict类型的用法

defaultdict 主要用来需要对 value 做初始化的情形。对于字典来说,key 必须是 hashable,immutable,unique 的数据,而 value 可以是任意的...

Python数据类型之Dict字典实例详解

本文实例讲述了Python数据类型之Dict字典。分享给大家供大家参考,具体如下: dict字典 1.概述 dict也是一种存储方式,类似于list和tuple,但是,字典采用键—值(k...