Files
health-service/main.py
2026-09-04 17:01:12 +08:00

60 lines
1.7 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 config.database import get_db
from routers import routers
from service import agent_service
scheduler = BackgroundScheduler()
def article_job_task():
"""定时执行的任务"""
try:
print(f"今日资讯定时任务执行: {datetime.now()}")
agent_service.query_article_agent(get_db())
except Exception as e:
print(f"今日资讯定时任务异常: {e}")
def recipe_job_task():
"""定时执行的任务"""
try:
print(f"今日菜谱定时任务执行: {datetime.now()}")
agent_service.query_recipe_agent(get_db())
except Exception as e:
print(f"今日菜谱定时任务异常: {e}")
scheduler.add_job(article_job_task, trigger="cron", hour=2, minute=0, second=0, id="daily_gen_articles", 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)