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

相关文章

学习python之编写简单乘法口诀表实现代码

实现代码一、 #!/usr/bin/python x,y=9,9 lst=[(x,y,str(y)+'X'+str(x)+'='+str(x*y)) fo...

将Emacs打造成强大的Python代码编辑工具

将Emacs打造成强大的Python代码编辑工具

基本配置 Emacs本身提供了python-mode,输入M-x python-mode,就可以进入python模式。相应地,会在菜单栏出现Python菜单。当然,一般来讲,如果是.py...

使用TensorFlow-Slim进行图像分类的实现

参考 https://github.com/tensorflow/models/tree/master/slim 使用TensorFlow-Slim进行图像分类 准备 安装Tensor...

Pytorch入门之mnist分类实例

本文实例为大家分享了Pytorch入门之mnist分类的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -*-...

Python闭包实现计数器的方法

本文实例讲述了Python闭包实现计数器的方法。分享给大家供大家参考。具体实现方法如下: 先来看看专业的解释:闭包(Closure)是词法闭包(Lexical Closure)的简称,是...