feat: 采集按分组选表和固定时刻运行,号池可检查凭证,管理页不再退出
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
"""采集按每周某天或每月某日的时刻运行。时间按北京时间计算。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
ZONE = ZoneInfo("Asia/Shanghai")
|
||||
TIME_RE = re.compile(r"^(\d{2}):(\d{2})$")
|
||||
|
||||
|
||||
def parse_schedule(raw: object) -> dict:
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("请设置采集周期")
|
||||
mode = raw.get("mode")
|
||||
if mode not in {"weekly", "monthly"}:
|
||||
raise ValueError("请设置采集周期")
|
||||
hour, minute = _clock(raw.get("time"))
|
||||
if mode == "weekly":
|
||||
weekday = _int(raw.get("weekday"), "请选择星期")
|
||||
if weekday < 1 or weekday > 7:
|
||||
raise ValueError("请选择星期")
|
||||
return {"mode": mode, "weekday": weekday, "time": f"{hour:02d}:{minute:02d}"}
|
||||
month_day = _int(raw.get("monthDay"), "请选择日期")
|
||||
if month_day < 1 or month_day > 31:
|
||||
raise ValueError("请选择日期")
|
||||
return {"mode": mode, "monthDay": month_day, "time": f"{hour:02d}:{minute:02d}"}
|
||||
|
||||
|
||||
def next_run_at(schedule: dict, now: datetime) -> datetime:
|
||||
local = now.astimezone(ZONE)
|
||||
hour, minute = _clock(schedule["time"])
|
||||
if schedule["mode"] == "weekly":
|
||||
target = local.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
||||
target += timedelta(days=(schedule["weekday"] - 1 - local.weekday()) % 7)
|
||||
if target <= local:
|
||||
target += timedelta(days=7)
|
||||
else:
|
||||
target = _monthly(local.year, local.month, schedule["monthDay"], hour, minute)
|
||||
if target <= local:
|
||||
year, month = (local.year + 1, 1) if local.month == 12 else (local.year, local.month + 1)
|
||||
target = _monthly(year, month, schedule["monthDay"], hour, minute)
|
||||
return target.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _monthly(year: int, month: int, day: int, hour: int, minute: int) -> datetime:
|
||||
last = calendar.monthrange(year, month)[1]
|
||||
return datetime(year, month, min(day, last), hour, minute, tzinfo=ZONE)
|
||||
|
||||
|
||||
def _clock(value: object) -> tuple[int, int]:
|
||||
match = TIME_RE.fullmatch(str(value or ""))
|
||||
if not match:
|
||||
raise ValueError("请填写采集时间")
|
||||
hour, minute = int(match.group(1)), int(match.group(2))
|
||||
if hour > 23 or minute > 59:
|
||||
raise ValueError("请填写采集时间")
|
||||
return hour, minute
|
||||
|
||||
|
||||
def _int(value: object, message: str) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(message) from exc
|
||||
Reference in New Issue
Block a user