59 lines
1.6 KiB
Python
59 lines
1.6 KiB
Python
from contextlib import asynccontextmanager
|
|
from datetime import datetime
|
|
|
|
from apscheduler.schedulers.background import BackgroundScheduler
|
|
from fastapi import FastAPI
|
|
from starlette.middleware.cors import CORSMiddleware
|
|
|
|
from routers import routers
|
|
from service import agent_service
|
|
|
|
scheduler = BackgroundScheduler()
|
|
|
|
|
|
def tip_job_task():
|
|
"""定时执行的任务"""
|
|
try:
|
|
print(f"今日资讯定时任务执行: {datetime.now()}")
|
|
agent_service.query_tip_agent()
|
|
except Exception as e:
|
|
print(f"今日资讯定时任务异常: {e}")
|
|
|
|
def recipe_job_task():
|
|
"""定时执行的任务"""
|
|
try:
|
|
print(f"今日菜谱定时任务执行: {datetime.now()}")
|
|
agent_service.query_recipe_agent()
|
|
except Exception as e:
|
|
print(f"今日菜谱定时任务异常: {e}")
|
|
|
|
|
|
scheduler.add_job(tip_job_task, trigger="cron", hour=2, minute=0, second=0, id="daily_gen_tips", replace_existing=True)
|
|
scheduler.add_job(recipe_job_task, trigger="cron", hour=3, minute=0, second=0, id="daily_gen_recipes", replace_existing=True)
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
# ========== 服务启动阶段 ==========
|
|
if not scheduler.running:
|
|
scheduler.start()
|
|
print("调度器已启动")
|
|
|
|
yield # 此处服务正常运行,接收请求
|
|
|
|
# ========== 服务关闭阶段 ==========
|
|
scheduler.shutdown()
|
|
print("调度器已关闭")
|
|
|
|
|
|
app = FastAPI(title="AI Health Service", lifespan=lifespan)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
for router in routers:
|
|
app.include_router(router)
|