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

2019-07-2108:51:27后端程序开发Comments3,051 views字数 969阅读模式

下载:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/14259.html

pip install apscheduler文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/14259.html

pip install django-apscheduler文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/14259.html

将 django-apscheduler 加到项目中settings的INSTALLED_APPS中文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/14259.html

INSTALLED_APPS = [

  ....

  'django_apscheduler',

]

然后迁移文件后文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/14259.html

./manage.py migrate

生成两个表:django_apscheduler_djangojob 和 django_apscheduler_djangojobexecution文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/14259.html

这两个表用来管理你所需要的定时任务,然后就开始在任一view下写你需要实现的任务:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/14259.html

启动异步定时任务
 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 实现定时任务的例子就是小编分享给大家的全部内容了.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/14259.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/14259.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定