准备:
1.安装:pip install django-apscheduler
2.在settings注册app:
INSTALLED_APPS = (
.......
django_apscheduler,
)
3.注册后数据迁移
python manage.py migrate
迁移之后会生成两张表:
django_apscheduler_djangojob
django_apscheduler_djangojobexecution
实现:
在项目中任意views.py文件中:
1 from apscheduler.schedulers.background import BackgroundScheduler 2 from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job 3 4 scheduler = BackgroundScheduler() # 创建一个调度器对象 5 scheduler.add_jobstore(DjangoJobStore(), "default") # 添加一个作业 6 try: 7 # @register_job(scheduler, "interval", seconds=1)用interval方式 每1秒执行一次 8 @register_job(scheduler, 'cron', day_of_week='mon-sun', hour='8', minute='30', second='10', id='delete_stale_data') # 定时执行:这里定时为周一到周日每天早上8:30执行一次 9 def time_task(): 10 """定时的任务逻辑""" 11 print("delete_stale_data") 12 register_events(scheduler) 13 scheduler.start() 14 # scheduler.remove_job(time_task) # 移除定时任务 15 except Exception as e: 16 print(e) 17 scheduler.shutdown()