feat: 后端添加定时任务与启动时任务
This commit is contained in:
@@ -24,7 +24,7 @@ import time
|
||||
import asyncio
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
|
||||
from app.core import Config, Broadcast
|
||||
from app.core import Config, Broadcast, TaskManager
|
||||
from app.services import System
|
||||
from app.models.schema import *
|
||||
|
||||
@@ -44,6 +44,8 @@ async def connect_websocket(websocket: WebSocket):
|
||||
last_ping = time.monotonic()
|
||||
data = {}
|
||||
|
||||
await TaskManager.start_startup_queue()
|
||||
|
||||
while True:
|
||||
|
||||
try:
|
||||
|
||||
@@ -180,23 +180,6 @@ async def confirm_notice() -> OutBase:
|
||||
# return InfoOut(data=data)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/startuptask",
|
||||
summary="获取启动时运行的队列ID",
|
||||
response_model=InfoOut,
|
||||
status_code=200,
|
||||
)
|
||||
async def get_startup_task() -> InfoOut:
|
||||
|
||||
try:
|
||||
data = await Config.get_startup_task()
|
||||
except Exception as e:
|
||||
return InfoOut(
|
||||
code=500, status="error", message=f"{type(e).__name__}: {str(e)}", data={}
|
||||
)
|
||||
return InfoOut(data={"queueIdList": data})
|
||||
|
||||
|
||||
@router.post(
|
||||
"/webconfig",
|
||||
summary="获取配置分享中心的配置信息",
|
||||
|
||||
@@ -214,6 +214,13 @@ class QueueConfig(ConfigBase):
|
||||
),
|
||||
)
|
||||
|
||||
self.Data_LastTimedStart = ConfigItem(
|
||||
"Data",
|
||||
"LastTimedStart",
|
||||
"2000-01-01 00:00",
|
||||
DateTimeValidator("%Y-%m-%d %H:%M"),
|
||||
)
|
||||
|
||||
self.TimeSet = MultipleConfig([TimeSet])
|
||||
self.QueueItem = MultipleConfig([QueueItem])
|
||||
|
||||
@@ -1998,19 +2005,6 @@ class AppConfig(GlobalConfig):
|
||||
|
||||
return remote_web_config
|
||||
|
||||
async def get_startup_task(self):
|
||||
"""获取启动时需要运行的队列信息"""
|
||||
|
||||
logger.info("获取启动时需要运行的队列信息")
|
||||
data = [
|
||||
str(uid)
|
||||
for uid, queue in self.QueueConfig.items()
|
||||
if queue.get("Info", "StartUpEnabled")
|
||||
]
|
||||
logger.success("启动时需要运行的队列信息获取成功")
|
||||
|
||||
return data
|
||||
|
||||
async def save_maa_log(self, log_path: Path, logs: list, maa_result: str) -> bool:
|
||||
"""
|
||||
保存MAA日志并生成对应统计数据
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
import uuid
|
||||
import asyncio
|
||||
from functools import partial
|
||||
from typing import Dict, Optional
|
||||
from typing import Dict, Optional, Literal
|
||||
|
||||
from .config import Config, MaaConfig, GeneralConfig, QueueConfig
|
||||
from app.models.schema import WebSocketMessage
|
||||
@@ -41,7 +41,9 @@ class _TaskManager:
|
||||
|
||||
self.task_dict: Dict[uuid.UUID, asyncio.Task] = {}
|
||||
|
||||
async def add_task(self, mode: str, uid: str) -> uuid.UUID:
|
||||
async def add_task(
|
||||
self, mode: Literal["自动代理", "人工排查", "设置脚本"], uid: str
|
||||
) -> uuid.UUID:
|
||||
"""
|
||||
添加任务
|
||||
|
||||
@@ -331,5 +333,22 @@ class _TaskManager:
|
||||
).model_dump()
|
||||
)
|
||||
|
||||
async def start_startup_queue(self):
|
||||
"""开始运行启动时运行的调度队列"""
|
||||
|
||||
logger.info("开始运行启动时任务")
|
||||
for uid, queue in Config.QueueConfig.items():
|
||||
|
||||
if queue.get("Info", "StartUpEnabled") and uid not in self.task_dict:
|
||||
logger.info(f"启动时需要运行的队列:{uid}")
|
||||
task_id = await TaskManager.add_task("自动代理", str(uid))
|
||||
await Config.send_json(
|
||||
WebSocketMessage(
|
||||
id="TaskManager", type="Signal", data={"newTask": str(task_id)}
|
||||
).model_dump()
|
||||
)
|
||||
|
||||
logger.success("启动时任务开始运行")
|
||||
|
||||
|
||||
TaskManager = _TaskManager()
|
||||
|
||||
@@ -24,7 +24,9 @@ from datetime import datetime
|
||||
|
||||
from app.services import Matomo, System
|
||||
from app.utils import get_logger
|
||||
from .config import Config
|
||||
from app.models.schema import WebSocketMessage
|
||||
from .config import Config, QueueConfig
|
||||
from .task_manager import TaskManager
|
||||
|
||||
|
||||
logger = get_logger("主业务定时器")
|
||||
@@ -39,6 +41,7 @@ class _MainTimer:
|
||||
while True:
|
||||
|
||||
await self.set_silence()
|
||||
await self.timed_start()
|
||||
|
||||
await asyncio.sleep(1)
|
||||
|
||||
@@ -69,6 +72,39 @@ class _MainTimer:
|
||||
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
async def timed_start(self):
|
||||
"""定时启动代理任务"""
|
||||
|
||||
curtime = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
for uid, queue in Config.QueueConfig.items():
|
||||
|
||||
if not isinstance(queue, QueueConfig) or not queue.get(
|
||||
"Info", "TimeEnabled"
|
||||
):
|
||||
continue
|
||||
|
||||
# 避免重复调起任务
|
||||
if curtime == Config.get("Data", "LastTimeStarted"):
|
||||
continue
|
||||
|
||||
for time_set in queue.TimeSet.values():
|
||||
if (
|
||||
time_set.get("Info", "Enabled")
|
||||
and curtime[11:16] == time_set.get("Info", "Time")
|
||||
and uid not in Config.task_dict
|
||||
):
|
||||
logger.info(f"定时唤起任务:{uid}")
|
||||
task_id = await TaskManager.add_task("自动代理", str(uid))
|
||||
|
||||
await Config.send_json(
|
||||
WebSocketMessage(
|
||||
id="TaskManager",
|
||||
type="Signal",
|
||||
data={"newTask": str(task_id)},
|
||||
).model_dump()
|
||||
)
|
||||
|
||||
async def set_silence(self):
|
||||
"""静默模式通过模拟老板键来隐藏模拟器窗口"""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user