Commit b45c55be by 江名洋

feat(scheduler): Enhance shutdown handling and task execution

- Added signal handlers for graceful shutdown in the FastAPI lifespan.
- Updated SchedulerManager to check for shutdown requests before executing tasks.
- Refactored task execution to run in daemon threads for improved responsiveness.
- Adjusted timeout settings for scheduler shutdown to ensure timely application exit.
1 parent 616e411a
Showing 152 changed files with 131 additions and 41 deletions
...@@ -106,7 +106,6 @@ class SchedulerManager: ...@@ -106,7 +106,6 @@ class SchedulerManager:
"""策略效果分析定时任务""" """策略效果分析定时任务"""
logger.info(f"[Scheduler] Start sync_strategy_analysis at {datetime.now()}") logger.info(f"[Scheduler] Start sync_strategy_analysis at {datetime.now()}")
try: try:
import asyncio
from app.services.strategy_service import get_task_state from app.services.strategy_service import get_task_state
state = get_task_state() state = get_task_state()
if state.get("running"): if state.get("running"):
...@@ -150,7 +149,7 @@ class SchedulerManager: ...@@ -150,7 +149,7 @@ class SchedulerManager:
@classmethod @classmethod
async def sync_dws_task(cls): async def sync_dws_task(cls):
"""DWS 数据加工定时任务:每天凌晨1点执行,日期范围从上月26号到今天""" """DWS 数据加工定时任务:每天凌晨1点执行,日期范围从上月26号到当天"""
logger.info(f"[Scheduler] Start sync_dws_task at {datetime.now()}") logger.info(f"[Scheduler] Start sync_dws_task at {datetime.now()}")
try: try:
today = date.today() today = date.today()
......
...@@ -189,6 +189,24 @@ GROUP_LABELS = [ ...@@ -189,6 +189,24 @@ GROUP_LABELS = [
("人工核对列", 54, 56), ("人工核对列", 54, 56),
] ]
# 模板示例数据行(含 Excel 公式),build_report 复制 sheet 后从此行提取公式
FORMULA_TEMPLATE_ROW = 5
# 表头合并配置 — 与输出模板002完全一致 (label, start_col, end_col, start_row, end_row),列 0-based
HEADER_MERGE_GROUPS = [
("基础门店信息\n标红为主机厂无数据,取产值表交付数为分母", 0, 9, 1, 2),
("主机厂数据", 10, 16, 1, 2),
("产值表数据", 17, 29, 1, 1),
("月度渗透率(分母为主机厂交付数)", 17, 29, 2, 2),
("生态系数", 30, 33, 1, 2),
("主机厂采购差异\n主机厂-产值表系统订单数", 34, 36, 1, 2),
("当前转化率", 37, 39, 1, 2),
("需达标转化率", 40, 42, 1, 2),
("需达标订单数差额", 44, 46, 1, 2),
("赔付金额\n(成本价:整车*0.55+安心包*0.65+电池*0.65)", 47, 49, 1, 2),
("人工核对列", 54, 56, 1, 1),
]
class AnalysisService: class AnalysisService:
"""问界生态系数分析服务""" """问界生态系数分析服务"""
...@@ -563,7 +581,7 @@ class AnalysisService: ...@@ -563,7 +581,7 @@ class AnalysisService:
placeholders = ", ".join(["%s"] * len(store_names)) placeholders = ", ".join(["%s"] * len(store_names))
sql = f""" sql = f"""
SELECT SELECT
go.merchant_name AS store_name, sm.merchant_name AS store_name,
SUM(IFNULL(gso.total_price, 0) - IFNULL(gso.refund_amount, 0)) AS output_value SUM(IFNULL(gso.total_price, 0) - IFNULL(gso.refund_amount, 0)) AS output_value
FROM ods_goods_order go FROM ods_goods_order go
INNER JOIN ods_goods_sub_order gso INNER JOIN ods_goods_sub_order gso
...@@ -573,12 +591,14 @@ class AnalysisService: ...@@ -573,12 +591,14 @@ class AnalysisService:
INNER JOIN ods_goods_order_customer goc INNER JOIN ods_goods_order_customer goc
ON go.order_code = goc.order_code ON go.order_code = goc.order_code
AND goc.car_childs_brand_id = 2695 AND goc.car_childs_brand_id = 2695
LEFT JOIN ods_service_merchant sm
ON go.merchant_id = sm.merchant_id AND sm.deleted_flag = 'N'
WHERE go.deleted_flag = 'N' WHERE go.deleted_flag = 'N'
AND go.status IN (4, 6, 12) AND go.status IN (4, 6, 12)
AND DATE(go.install_upgrade_time) >= %s AND DATE(go.install_upgrade_time) >= %s
AND DATE(go.install_upgrade_time) <= %s AND DATE(go.install_upgrade_time) <= %s
AND go.merchant_name IN ({placeholders}) AND sm.merchant_name IN ({placeholders})
GROUP BY go.merchant_name GROUP BY sm.merchant_name
""" """
params = [start_date, end_date] + list(store_names) params = [start_date, end_date] + list(store_names)
...@@ -810,12 +830,12 @@ class AnalysisService: ...@@ -810,12 +830,12 @@ class AnalysisService:
return levels return levels
@staticmethod @staticmethod
def _extract_formulas_from_template(ws): def _extract_formulas_from_template(ws, template_row: int = FORMULA_TEMPLATE_ROW):
"""从模板第4行提取公式映射和外部引用列集合""" """从模板示例行提取公式映射和外部引用列集合(输出模板002公式在第5行)"""
formula_map = {} formula_map = {}
skip_external_cols = set() skip_external_cols = set()
for col in range(1, 58): for col in range(1, 58):
cell = ws.cell(row=4, column=col) cell = ws.cell(row=template_row, column=col)
raw = cell.value raw = cell.value
if raw is None: if raw is None:
continue continue
...@@ -841,6 +861,48 @@ class AnalysisService: ...@@ -841,6 +861,48 @@ class AnalysisService:
ws.cell(row=r, column=c).value = None ws.cell(row=r, column=c).value = None
@staticmethod @staticmethod
def _apply_conditional_formatting(ws, template_ws, data_start_row: int):
"""从模板复制条件格式规则,并将 sqref 映射到实际数据起始行(保留规则样式不变)"""
from copy import deepcopy
tpl_groups = list(template_ws.conditional_formatting)
if not tpl_groups:
logger.warning("Template has no conditional formatting rules")
return
ws.conditional_formatting._cf_rules.clear()
end_row = 1048576
ds = data_start_row
grade_cols = ("AZ", "BA", "BB", "BC", "BD", "BE")
def _add(sqref: str, rule):
ws.conditional_formatting.add(sqref, deepcopy(rule))
# 1) A列:门店名重复标红
if tpl_groups[0].rules:
_add(f"A{ds}:A8000", tpl_groups[0].rules[0])
# 2) AP列:值为「否」
if len(tpl_groups) > 1 and tpl_groups[1].rules:
_add(f"AP{ds}:AP{end_row}", tpl_groups[1].rules[0])
# 3) 门店等级三色(黄/绿/红)— 覆盖模板中 AZ~BE 各列
if len(tpl_groups) > 2 and tpl_groups[2].rules:
grade_sqref = " ".join(f"{c}{ds}:{c}{end_row}" for c in grade_cols)
for rule in tpl_groups[2].rules:
_add(grade_sqref, rule)
# 4) AP/AR列:值为「是」
if len(tpl_groups) > 3 and tpl_groups[3].rules:
_add(f"AP{ds}:AP{end_row} AR{ds}:AR{end_row}", tpl_groups[3].rules[0])
logger.info(
f"Applied {len(list(ws.conditional_formatting))} conditional formatting groups "
f"from row {ds}"
)
@staticmethod
def _process_one_sheet(ws, store_subset, factory_sheets, start_date, end_date, def _process_one_sheet(ws, store_subset, factory_sheets, start_date, end_date,
formula_map, skip_external_cols, start_row=4): formula_map, skip_external_cols, start_row=4):
"""对单张sheet写入数据:查DB → 写数据行,返回下一个可用行号""" """对单张sheet写入数据:查DB → 写数据行,返回下一个可用行号"""
...@@ -942,23 +1004,13 @@ class AnalysisService: ...@@ -942,23 +1004,13 @@ class AnalysisService:
# 提取公式(在清除任何数据之前) # 提取公式(在清除任何数据之前)
formula_map, skip_external_cols = AnalysisService._extract_formulas_from_template(ws_template) formula_map, skip_external_cols = AnalysisService._extract_formulas_from_template(ws_template)
# openpyxl 的 copy_worksheet 不复制条件格式,需手动保存 # openpyxl 的 copy_worksheet 不复制条件格式,数据写完后按实际行号重新应用
from copy import copy as shallow_copy
cf_rules = [(str(cf.sqref), [shallow_copy(r) for r in cf.rules]) for cf in ws_template.conditional_formatting]
# 复制一份模板sheet
ws = wb.copy_worksheet(ws_template) ws = wb.copy_worksheet(ws_template)
ws.title = sheet_name ws.title = sheet_name
# 保留原始"模板"sheet(隐藏) # 保留原始"模板"sheet(隐藏,供公式/条件格式提取)
ws_template.sheet_state = 'hidden' ws_template.sheet_state = 'hidden'
# 将条件格式复制到新sheet
for sqref, rules in cf_rules:
for rule in rules:
ws.conditional_formatting.add(sqref, rule)
logger.info(f"Copied {len(cf_rules)} conditional formatting rules")
# 清除数据行(保留表头1-3行) # 清除数据行(保留表头1-3行)
AnalysisService._clear_sheet_data(ws) AnalysisService._clear_sheet_data(ws)
...@@ -986,6 +1038,7 @@ class AnalysisService: ...@@ -986,6 +1038,7 @@ class AnalysisService:
ws.row_dimensions[row].height = 24 ws.row_dimensions[row].height = 24
next_row = 4 next_row = 4
first_data_row = None
# 生态数据标签行 # 生态数据标签行
eco_label_text = f"▲ 生态数据({ecology_start} ~ {ecology_end})" if ecology_start and ecology_end else "▲ 生态数据" eco_label_text = f"▲ 生态数据({ecology_start} ~ {ecology_end})" if ecology_start and ecology_end else "▲ 生态数据"
...@@ -995,6 +1048,8 @@ class AnalysisService: ...@@ -995,6 +1048,8 @@ class AnalysisService:
# 处理生态数据(上部) # 处理生态数据(上部)
if has_ecology: if has_ecology:
if first_data_row is None:
first_data_row = next_row
next_row = AnalysisService._process_one_sheet( next_row = AnalysisService._process_one_sheet(
ws, ecology_stores, ecology_factory, ws, ecology_stores, ecology_factory,
ecology_start, ecology_end, formula_map, skip_external_cols, start_row=next_row) ecology_start, ecology_end, formula_map, skip_external_cols, start_row=next_row)
...@@ -1014,6 +1069,8 @@ class AnalysisService: ...@@ -1014,6 +1069,8 @@ class AnalysisService:
if not has_ecology: if not has_ecology:
_write_separator(ws, next_row, nat_label_text) _write_separator(ws, next_row, nat_label_text)
next_row += 1 next_row += 1
if first_data_row is None:
first_data_row = next_row
next_row = AnalysisService._process_one_sheet( next_row = AnalysisService._process_one_sheet(
ws, nature_stores, nature_factory, ws, nature_stores, nature_factory,
nature_start, nature_end, formula_map, skip_external_cols, start_row=next_row) nature_start, nature_end, formula_map, skip_external_cols, start_row=next_row)
...@@ -1021,11 +1078,11 @@ class AnalysisService: ...@@ -1021,11 +1078,11 @@ class AnalysisService:
reason = "no stores" if len(nature_stores) == 0 else "no factory data" reason = "no stores" if len(nature_stores) == 0 else "no factory data"
logger.info(f"Skipping nature section ({reason})") logger.info(f"Skipping nature section ({reason})")
# 设置自动筛选(覆盖表头行到数据末行) # 数据写完后,按实际起始行重新应用模板条件格式(copy_worksheet 不复制 CF)
# 取消第1行合并单元格(避免合并单元格导致筛选灰色不可用) if first_data_row is not None:
for merged_range in list(ws.merged_cells.ranges): AnalysisService._apply_conditional_formatting(ws, ws_template, first_data_row)
if merged_range.min_row == 1 and merged_range.max_row == 1:
ws.unmerge_cells(str(merged_range)) # 设置自动筛选(覆盖第3行列名到数据末行;保留第1-2行分组合并,如 R1:AD1)
last_col_letter = get_column_letter(len(OUTPUT_HEADERS)) last_col_letter = get_column_letter(len(OUTPUT_HEADERS))
ws.auto_filter.ref = f"A3:{last_col_letter}{next_row - 1}" ws.auto_filter.ref = f"A3:{last_col_letter}{next_row - 1}"
...@@ -1044,21 +1101,23 @@ class AnalysisService: ...@@ -1044,21 +1101,23 @@ class AnalysisService:
@staticmethod @staticmethod
def _write_header(ws): def _write_header(ws):
"""写入两层表头""" """写入两层表头,合并单元格结构与输出模板002一致"""
# 第1行:分组标签 # 清除第1-3行已有合并,避免重复 merge 报错
for label, start_col, end_col in GROUP_LABELS: for merged in list(ws.merged_cells.ranges):
if start_col <= end_col: if merged.min_row <= 3 and merged.max_row <= 3:
cell = ws.cell(row=1, column=start_col + 1, value=label) ws.unmerge_cells(str(merged))
for label, start_col, end_col, start_row, end_row in HEADER_MERGE_GROUPS:
if start_col > end_col:
continue
sc, ec = start_col + 1, end_col + 1
cell = ws.cell(row=start_row, column=sc, value=label)
cell.font = GROUP_FONT cell.font = GROUP_FONT
cell.fill = GROUP_FILL cell.fill = GROUP_FILL
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
if end_col > start_col: if end_row > start_row or ec > sc:
ws.merge_cells( ws.merge_cells(start_row=start_row, start_column=sc, end_row=end_row, end_column=ec)
start_row=1, start_column=start_col + 1,
end_row=1, end_column=end_col + 1
)
# 第2行:周期信息(空行,给备注用)
ws.row_dimensions[2].height = 20 ws.row_dimensions[2].height = 20
# 第3行:具体列名 # 第3行:具体列名
...@@ -1078,7 +1137,7 @@ class AnalysisService: ...@@ -1078,7 +1137,7 @@ class AnalysisService:
Args: Args:
db_perf: 从数据库查询的门店产值表数据 db_perf: 从数据库查询的门店产值表数据
start_date/end_date: 查询日期范围 start_date/end_date: 查询日期范围
formula_map: 模板第4行的公式映射 {col: formula_text},有公式的列直接写入公式 formula_map: 模板示例行的公式映射 {col: formula_text},有公式的列直接写入公式
skip_external_cols: 跳过公式写入的列(外部引用),使用Python计算值替代 skip_external_cols: 跳过公式写入的列(外部引用),使用Python计算值替代
start_row: 起始行号,默认4 start_row: 起始行号,默认4
db_output: 从 goods_sub_order 查询的产值 {store_name: float} db_output: 从 goods_sub_order 查询的产值 {store_name: float}
...@@ -1447,13 +1506,14 @@ class AnalysisService: ...@@ -1447,13 +1506,14 @@ class AnalysisService:
# ========== 去除服务商 (BE, col 57) ========== # ========== 去除服务商 (BE, col 57) ==========
_style_cell(row_num, 57, "服务商" if str(store_perf.get("operation_mode", "")).strip() != "直营" else "") _style_cell(row_num, 57, "服务商" if str(store_perf.get("operation_mode", "")).strip() != "直营" else "")
# ========== 写入公式列(模板第4行有公式的列,跳过外部引用列)========== # ========== 写入公式列(模板示例行有公式的列,跳过外部引用列)==========
for col_idx, formula_text in formula_map.items(): for col_idx, formula_text in formula_map.items():
if col_idx in skip_external_cols: if col_idx in skip_external_cols:
continue # 外部引用列已用Python值写入 continue # 外部引用列已用Python值写入
# 调整公式:将行号4替换为当前行号 # 调整公式:将模板示例行号替换为当前数据行号
tpl_row = FORMULA_TEMPLATE_ROW
adjusted = re.sub( adjusted = re.sub(
r'([A-Z]{1,3})4\b', rf'([A-Z]{{1,3}}){tpl_row}\b',
lambda m: f'{m.group(1)}{row_num}', lambda m: f'{m.group(1)}{row_num}',
formula_text formula_text
) )
......
...@@ -93,7 +93,6 @@ async def lifespan(app: FastAPI): ...@@ -93,7 +93,6 @@ async def lifespan(app: FastAPI):
# 关闭时执行 # 关闭时执行
print("[*] Stopping Data Analyze WebUI...") print("[*] Stopping Data Analyze WebUI...")
try: try:
# 强制设置停止超时,防止由于任务阻塞导致进程无法退出
await asyncio.wait_for(SchedulerManager.stop(), timeout=5.0) await asyncio.wait_for(SchedulerManager.stop(), timeout=5.0)
except asyncio.TimeoutError: except asyncio.TimeoutError:
print("[!] Scheduler stop timed out, forcing exit.") print("[!] Scheduler stop timed out, forcing exit.")
...@@ -184,6 +183,37 @@ async def health(): ...@@ -184,6 +183,37 @@ async def health():
if __name__ == "__main__": if __name__ == "__main__":
import signal
import threading
# Ctrl+C 后若优雅关闭卡住,超时后强制结束本进程(逻辑仅在此入口生效)
FORCE_EXIT_SECONDS = 3
_force_exit_state = {"armed": False}
_force_exit_lock = threading.Lock()
def _arm_force_exit():
with _force_exit_lock:
if _force_exit_state["armed"]:
return
_force_exit_state["armed"] = True
def _force_kill():
time.sleep(FORCE_EXIT_SECONDS)
print(f"[!] {FORCE_EXIT_SECONDS}s 内未能正常退出,强制结束进程。")
os._exit(1)
threading.Thread(target=_force_kill, daemon=True, name="force-exit").start()
def _on_exit_signal(signum, _frame):
label = "Ctrl+C" if signum == signal.SIGINT else f"signal {signum}"
print(f"[*] 收到退出信号 ({label}),正在关闭服务...")
_arm_force_exit()
raise KeyboardInterrupt
signal.signal(signal.SIGINT, _on_exit_signal)
if hasattr(signal, "SIGTERM"):
signal.signal(signal.SIGTERM, _on_exit_signal)
# 端口指定 9500,root_path 适配子路径部署(如 /daw) # 端口指定 9500,root_path 适配子路径部署(如 /daw)
uvicorn.run( uvicorn.run(
"main:app", "main:app",
...@@ -191,4 +221,5 @@ if __name__ == "__main__": ...@@ -191,4 +221,5 @@ if __name__ == "__main__":
port=9500, port=9500,
reload=settings.APP_DEBUG, reload=settings.APP_DEBUG,
root_path=settings.ROOT_PATH or "", root_path=settings.ROOT_PATH or "",
timeout_graceful_shutdown=FORCE_EXIT_SECONDS,
) )
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!