下载:
pip install apscheduler
pip install django-apscheduler
将 django-apscheduler 加到项目中settings的INSTALLED_APPS中
- INSTALLED_APPS = [
-
- ....
-
- 'django_apscheduler',
-
- ]
然后迁移文件后
生成两个表: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 实现定时任务的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持w3xue。