feat(schedule):cron支持图形,RoHS检核增加进度显示
This commit is contained in:
1 parent
6d0e78be81
commit
f5aac9c893
46 files changed
+1987
-221
No files matched your search
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
backend/app/services/schedule/cron_util.py
|
||||
排程 Cron 表达式规范化与校验辅助。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def normalize_cron_expr(expr: str | None) -> str:
|
||||
"""
|
||||
修正常见笔误:* 12,17 * * *(小时内每分钟)→ 0 12,17 * * *(整点)。
|
||||
"""
|
||||
text = str(expr or '').strip()
|
||||
parts = text.split()
|
||||
if len(parts) == 5 and parts[0] == '*' and parts[1] != '*':
|
||||
parts[0] = '0'
|
||||
return ' '.join(parts)
|
||||
return text
|
||||
|
||||
|
||||
def is_risky_cron_expr(expr: str | None) -> bool:
|
||||
"""分钟为 * 且小时已限定时,会在该小时内每分钟触发。"""
|
||||
text = str(expr or '').strip()
|
||||
parts = text.split()
|
||||
return len(parts) == 5 and parts[0] == '*' and parts[1] != '*'
|
||||
@@ -9,6 +9,17 @@ from sqlalchemy.orm import joinedload
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.response_utils import utc_iso
|
||||
from app.services.schedule.timezone_util import (
|
||||
DEFAULT_SCHEDULE_TIMEZONE,
|
||||
compute_next_run_at,
|
||||
normalize_schedule_timezone,
|
||||
)
|
||||
|
||||
|
||||
def _schedule_timezone_label(task: ScheduleTask | None = None) -> str:
|
||||
if task is not None:
|
||||
return normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
|
||||
return DEFAULT_SCHEDULE_TIMEZONE
|
||||
|
||||
|
||||
def _as_naive_utc(dt: datetime | None) -> datetime | None:
|
||||
@@ -28,6 +39,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
|
||||
'owner_user_id': task.owner_user_id,
|
||||
'owner_username': task.owner.username if task.owner else None,
|
||||
'cron_expr': task.cron_expr,
|
||||
'schedule_timezone': _schedule_timezone_label(task),
|
||||
'wait_seconds': task.wait_seconds,
|
||||
'dify_agent_id': task.dify_agent_id,
|
||||
'platform_api_path': task.platform_api_path,
|
||||
@@ -82,6 +94,17 @@ def serialize_run(run: ScheduleRun) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _repair_next_run_if_needed(task: ScheduleTask) -> bool:
|
||||
"""启用中但 next_run_at 为空时补算,返回是否发生修改。"""
|
||||
if not task.enabled or not str(task.cron_expr or '').strip():
|
||||
return False
|
||||
if task.next_run_at is not None:
|
||||
return False
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
return task.next_run_at is not None
|
||||
|
||||
|
||||
def list_tasks() -> list[dict]:
|
||||
latest_run_subquery = (
|
||||
db.session.query(
|
||||
@@ -99,6 +122,13 @@ def list_tasks() -> list[dict]:
|
||||
.order_by(ScheduleTask.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
repaired = False
|
||||
for task, _last_status in rows:
|
||||
if _repair_next_run_if_needed(task):
|
||||
repaired = True
|
||||
if repaired:
|
||||
db.session.commit()
|
||||
|
||||
return [serialize_task(task, last_status=last_status) for task, last_status in rows]
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from croniter import croniter
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
@@ -15,6 +14,8 @@ from app.services.schedule import normalize_platform_api_path, resolve_schedule_
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone, utc_now_naive
|
||||
|
||||
_worker_started = False
|
||||
_worker_lock = threading.Lock()
|
||||
@@ -160,6 +161,7 @@ def create_task(
|
||||
schedule_type: str,
|
||||
owner_user_id: int,
|
||||
cron_expr: str,
|
||||
schedule_timezone: str | None = None,
|
||||
wait_seconds: int,
|
||||
dify_agent_id: int | None,
|
||||
platform_api_path: str | None,
|
||||
@@ -168,12 +170,14 @@ def create_task(
|
||||
enabled: bool,
|
||||
actor_id: int | None,
|
||||
) -> ScheduleTask:
|
||||
cron_expr = normalize_cron_expr(cron_expr)
|
||||
task = ScheduleTask(
|
||||
schedule_no=_generate_schedule_no(),
|
||||
name=name,
|
||||
schedule_type="platform_app",
|
||||
owner_user_id=owner_user_id,
|
||||
cron_expr=cron_expr,
|
||||
schedule_timezone=normalize_schedule_timezone(schedule_timezone),
|
||||
wait_seconds=max(0, int(wait_seconds or 0)),
|
||||
dify_agent_id=dify_agent_id,
|
||||
platform_api_path=normalize_platform_api_path(platform_api_path) or None,
|
||||
@@ -184,11 +188,8 @@ def create_task(
|
||||
updated_by=actor_id,
|
||||
)
|
||||
if task.enabled and task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
if task.next_run_at is None:
|
||||
task.enabled = False
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -200,13 +201,20 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
|
||||
"name",
|
||||
"owner_user_id",
|
||||
"cron_expr",
|
||||
"schedule_timezone",
|
||||
"wait_seconds",
|
||||
"dify_agent_id",
|
||||
"notify_enabled",
|
||||
"enabled",
|
||||
]:
|
||||
if key in payload:
|
||||
setattr(task, key, payload[key])
|
||||
if key == "schedule_timezone":
|
||||
value = normalize_schedule_timezone(payload[key])
|
||||
elif key == "cron_expr":
|
||||
value = normalize_cron_expr(str(payload[key] or ""))
|
||||
else:
|
||||
value = payload[key]
|
||||
setattr(task, key, value)
|
||||
if "platform_api_path" in payload:
|
||||
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
|
||||
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
|
||||
@@ -222,11 +230,8 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
|
||||
task.schedule_type = "platform_app"
|
||||
|
||||
if task.enabled and task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
else:
|
||||
task.next_run_at = None
|
||||
|
||||
@@ -258,11 +263,7 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
db.session.commit()
|
||||
|
||||
if task.cron_expr and trigger_type == "cron":
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
|
||||
db.session.commit()
|
||||
|
||||
start_ts = time.time()
|
||||
@@ -402,15 +403,12 @@ def start_scheduler(app):
|
||||
stale = db.session.query(ScheduleTask).filter(
|
||||
ScheduleTask.enabled.is_(True),
|
||||
ScheduleTask.next_run_at.isnot(None),
|
||||
ScheduleTask.next_run_at <= datetime.utcnow(),
|
||||
ScheduleTask.next_run_at <= utc_now_naive(),
|
||||
).all()
|
||||
for t in stale:
|
||||
if t.cron_expr:
|
||||
try:
|
||||
it = croniter(t.cron_expr, datetime.utcnow())
|
||||
t.next_run_at = it.get_next(datetime)
|
||||
except Exception:
|
||||
t.next_run_at = None
|
||||
t.next_run_at = compute_next_run_at(t.cron_expr, timezone_name=getattr(t, "schedule_timezone", None))
|
||||
if t.next_run_at is None:
|
||||
t.enabled = False
|
||||
else:
|
||||
t.next_run_at = None
|
||||
@@ -431,7 +429,7 @@ def start_scheduler(app):
|
||||
|
||||
while True:
|
||||
try:
|
||||
now = datetime.utcnow()
|
||||
now = utc_now_naive()
|
||||
due_tasks = db.session.query(ScheduleTask).filter(
|
||||
ScheduleTask.enabled.is_(True),
|
||||
ScheduleTask.next_run_at.isnot(None),
|
||||
@@ -444,11 +442,7 @@ def start_scheduler(app):
|
||||
).first()
|
||||
if has_running:
|
||||
if task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
|
||||
db.session.commit()
|
||||
continue
|
||||
try:
|
||||
@@ -458,11 +452,8 @@ def start_scheduler(app):
|
||||
db.session.rollback()
|
||||
|
||||
if task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
|
||||
if task.next_run_at is None:
|
||||
task.enabled = False
|
||||
else:
|
||||
task.next_run_at = None
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
backend/app/services/schedule/timezone_util.py
|
||||
排程 Cron 时区:优先按任务自己的 IANA 时区解析表达式,数据库存储 UTC naive。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone, tzinfo
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from croniter import croniter
|
||||
from flask import current_app
|
||||
|
||||
DEFAULT_SCHEDULE_TIMEZONE = 'Asia/Shanghai'
|
||||
|
||||
# 环境未安装 tzdata 时,用固定 UTC 偏移回退(不含夏令时)
|
||||
_FIXED_TZ_FALLBACKS: dict[str, tzinfo] = {
|
||||
'Asia/Shanghai': timezone(timedelta(hours=8)),
|
||||
'Asia/Taipei': timezone(timedelta(hours=8)),
|
||||
'Asia/Hong_Kong': timezone(timedelta(hours=8)),
|
||||
'UTC': timezone.utc,
|
||||
}
|
||||
|
||||
|
||||
def get_schedule_timezone_name(timezone_name: str | None = None) -> str:
|
||||
"""解析排程时区名称;优先使用任务时区,其次回退到系统默认时区。"""
|
||||
return (timezone_name or current_app.config.get('SCHEDULE_TIMEZONE') or DEFAULT_SCHEDULE_TIMEZONE).strip()
|
||||
|
||||
|
||||
def resolve_schedule_tzinfo(timezone_name: str | None = None) -> tzinfo:
|
||||
"""
|
||||
将 IANA 时区名解析为 tzinfo。
|
||||
|
||||
优先使用 zoneinfo;若运行环境缺少 tzdata(常见于未 pip install tzdata 的容器/venv),
|
||||
对常用业务时区回退到固定 UTC 偏移。
|
||||
"""
|
||||
name = get_schedule_timezone_name(timezone_name)
|
||||
try:
|
||||
return ZoneInfo(name)
|
||||
except Exception:
|
||||
fallback = _FIXED_TZ_FALLBACKS.get(name)
|
||||
if fallback is not None:
|
||||
_log_tz_fallback_once(name)
|
||||
return fallback
|
||||
default_fallback = _FIXED_TZ_FALLBACKS[DEFAULT_SCHEDULE_TIMEZONE]
|
||||
_log_tz_fallback_once(name, fallback_to=DEFAULT_SCHEDULE_TIMEZONE)
|
||||
return default_fallback
|
||||
|
||||
|
||||
def get_schedule_timezone(timezone_name: str | None = None) -> tzinfo:
|
||||
"""将排程时区名称转换为 tzinfo,供 croniter 计算当地执行时间。"""
|
||||
return resolve_schedule_tzinfo(timezone_name)
|
||||
|
||||
|
||||
def normalize_schedule_timezone(timezone_name: str | None) -> str:
|
||||
"""校验并标准化 IANA 时区名;无法通过 zoneinfo 校验时仍保留可回退的名称。"""
|
||||
text = get_schedule_timezone_name(timezone_name)
|
||||
try:
|
||||
ZoneInfo(text)
|
||||
return text
|
||||
except Exception:
|
||||
if text in _FIXED_TZ_FALLBACKS:
|
||||
return text
|
||||
return DEFAULT_SCHEDULE_TIMEZONE
|
||||
|
||||
|
||||
def utc_now_naive() -> datetime:
|
||||
"""返回 UTC naive datetime,统一用于数据库字段比较。"""
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def to_utc_naive(dt: datetime) -> datetime:
|
||||
"""将 aware datetime 转为 UTC naive;naive 输入保持不变。"""
|
||||
if dt.tzinfo is None:
|
||||
return dt
|
||||
return dt.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def compute_next_run_at(
|
||||
cron_expr: str,
|
||||
*,
|
||||
base_utc_naive: datetime | None = None,
|
||||
timezone_name: str | None = None,
|
||||
) -> datetime | None:
|
||||
"""
|
||||
按排程业务时区计算下次执行时刻,返回 UTC naive 供入库与 worker 比较。
|
||||
|
||||
:param cron_expr: 5 段标准 Cron
|
||||
:param base_utc_naive: 基准时刻(UTC naive);默认取当前时刻
|
||||
"""
|
||||
text = str(cron_expr or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
tz_name = normalize_schedule_timezone(timezone_name)
|
||||
try:
|
||||
tz = resolve_schedule_tzinfo(tz_name)
|
||||
if base_utc_naive is None:
|
||||
base_aware = datetime.now(tz)
|
||||
else:
|
||||
base_aware = base_utc_naive.replace(tzinfo=timezone.utc).astimezone(tz)
|
||||
itr = croniter(text, base_aware)
|
||||
return to_utc_naive(itr.get_next(datetime))
|
||||
except Exception as exc:
|
||||
try:
|
||||
current_app.logger.warning(
|
||||
"compute_next_run_at failed: %s cron=%s tz=%s",
|
||||
exc,
|
||||
text,
|
||||
tz_name,
|
||||
)
|
||||
except RuntimeError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
_logged_tz_fallbacks: set[str] = set()
|
||||
|
||||
|
||||
def _log_tz_fallback_once(requested: str, *, fallback_to: str | None = None) -> None:
|
||||
"""缺少 tzdata 时仅记录一次回退日志,避免刷屏。"""
|
||||
key = f'{requested}->{fallback_to or requested}'
|
||||
if key in _logged_tz_fallbacks:
|
||||
return
|
||||
_logged_tz_fallbacks.add(key)
|
||||
try:
|
||||
current_app.logger.warning(
|
||||
"tzdata unavailable; using fixed UTC offset fallback for schedule timezone %s%s. "
|
||||
"Install backend dependency tzdata (pip install tzdata).",
|
||||
requested,
|
||||
f' (fallback {fallback_to})' if fallback_to else '',
|
||||
)
|
||||
except RuntimeError:
|
||||
pass
|
||||
Reference in new issue
Block a user