File size: 2,145 Bytes
76b9762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
定时任务控制路由模块
"""

from fastapi import APIRouter, Request, HTTPException, status
from fastapi.responses import JSONResponse

from app.core.security import verify_auth_token
from app.scheduler.scheduled_tasks import start_scheduler, stop_scheduler
from app.log.logger import get_scheduler_routes

logger = get_scheduler_routes()

router = APIRouter(
    prefix="/api/scheduler",
    tags=["Scheduler"]
)

async def verify_token(request: Request):
    auth_token = request.cookies.get("auth_token")
    if not auth_token or not verify_auth_token(auth_token):
        logger.warning("Unauthorized access attempt to scheduler API")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"},
        )

@router.post("/start", summary="启动定时任务")
async def start_scheduler_endpoint(request: Request):
    """Start the background scheduler task"""
    await verify_token(request)
    try:
        logger.info("Received request to start scheduler.")
        start_scheduler()
        return JSONResponse(content={"message": "Scheduler started successfully."}, status_code=status.HTTP_200_OK)
    except Exception as e:
        logger.error(f"Error starting scheduler: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to start scheduler: {str(e)}"
        )

@router.post("/stop", summary="停止定时任务")
async def stop_scheduler_endpoint(request: Request):
    """Stop the background scheduler task"""
    await verify_token(request)
    try:
        logger.info("Received request to stop scheduler.")
        stop_scheduler()
        return JSONResponse(content={"message": "Scheduler stopped successfully."}, status_code=status.HTTP_200_OK)
    except Exception as e:
        logger.error(f"Error stopping scheduler: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to stop scheduler: {str(e)}"
        )