Files
health-service/main.py
2026-08-31 15:22:00 +08:00

51 lines
1.2 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 job_task():
"""定时执行的任务"""
try:
print(f"定时任务执行: {datetime.now()}")
agent_service.generate_tip_agent()
except Exception as e:
print(f"定时任务异常: {e}")
scheduler.add_job(job_task, trigger="cron", hour=2, minute=0, second=0, id="daily_gen_tips", 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)