转载:
https://zhuanlan.zhihu.com/p/46690789
在django的某个app启动apscheduler
ready方法会在django启动的时候执行,有一个bug,方法总是会同时执行两次
#apps.py from django.apps import AppConfig class JobscheduleConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'jobSchedule' def ready(self): import datetime from apscheduler.schedulers.background import BackgroundScheduler def job_func(text): print("当前时间:"+text, datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]) scheduler = BackgroundScheduler() scheduler.add_job(job_func, 'cron', second='0,10,20,30,40,50',args=("sss",)) scheduler.start()
bug解决
新建app,jobSchedule
一、在一级urls.py引入新app的urls
urlpatterns = [ ... path('jobSchedule/', include('jobSchedule.urls')), ]
二、在app的urls.py引入views.py
from django.urls import path from . import views app_name = 'jobSchedule' urlpatterns = [ path('', views.index, name='index'), ]
三、views.py
import datetime from apscheduler.schedulers.background import BackgroundScheduler def job_func(text): print("当前时间:" + text, datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]) scheduler = BackgroundScheduler() scheduler.add_job(job_func, 'cron', second='0,10,20,30,40,50', args=("sss",)) scheduler.start() def index(request): return None
这样就正常了