creación de scheduler.json para ejecución de servicio

This commit is contained in:
George committed 2026-08-04 09:34:44 -05:00
1 parent 839aad698d
commit 1c39f6f45f
11 files changed
+112 -400

No files matched your search

+34 -19
View File
@@ -9,6 +9,7 @@ from pathlib import Path
from dotenv import load_dotenv
import urllib3
# ============================================================================
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
load_dotenv()
@@ -24,18 +25,31 @@ from consulta_cpe import (
)
# ============================================================================
# CONFIGURACIÓN DE HORARIOS
# CONFIGURACIÓN DE HORARIOS (desde scheduler.json)
# ============================================================================
# (hora_inicio, min_inicio, hora_fin, min_fin, intervalo_segundos, modo)
HORARIOS = [
(6, 30, 13, 15, 300, "rapido"), # 06:30 - 13:15 -> cada 5 minutos
(13, 15, 14, 0, 3600, "full"), # 13:15 - 14:00 -> cada 1 hora
(14, 0, 17, 30, 300, "rapido"), # 14:00 - 17:30 -> cada 5 minutos
(17, 30, 21, 30, 3600, "full"), # 17:30 - 21:30 -> cada 1 hora
]
SCHEDULER_FILE = Path(__file__).parent / "scheduler.json"
# 0=lun, 1=mar, 2=mié, 3=jue, 4=vie, 5=sáb, 6=dom
DIAS_ACTIVOS = [0, 1, 2, 3, 4]
def _cargar_scheduler():
with open(SCHEDULER_FILE, encoding="utf-8") as f:
data = json.load(f)
horarios = [tuple(h) for h in data["HORARIOS"]]
return data["DIAS_ACTIVOS"], horarios
try:
DIAS_ACTIVOS, HORARIOS = _cargar_scheduler()
except Exception as e:
print(f"⚠️ Error cargando {SCHEDULER_FILE}: {e}. Usando defaults.")
# (hora_inicio, min_inicio, hora_fin, min_fin, intervalo_segundos, modo)
HORARIOS = [
(6, 30, 13, 15, 300, "rapido"), # 06:30 - 13:15 -> cada 5 minutos
(13, 15, 14, 0, 3600, "full"), # 13:15 - 14:00 -> cada 1 hora
(14, 0, 17, 30, 300, "rapido"), # 14:00 - 17:30 -> cada 5 minutos
(17, 30, 21, 30, 3600, "full"), # 17:30 - 21:30 -> cada 1 hora
]
# 0=lun, 1=mar, 2=mié, 3=jue, 4=vie, 5=sáb, 6=dom
DIAS_ACTIVOS = [0, 1, 2, 3, 4]
_running = True
@@ -45,14 +59,14 @@ color_amarillo = "\033[93m"
color_rojo = "\033[91m"
color_fin = "\033[0m"
# ============================================================================
def ic(ok, texto_ok, texto_fail):
"""Icono + texto según estado."""
icono = "✅" if ok else "⚠️"
color = color_verde if ok else color_amarillo
return f"{icono} {color}{texto_ok if ok else texto_fail}{color_fin}"
# ============================================================================
def obtener_intervalo(dt: datetime) -> tuple[int, str] | None:
minutos = dt.hour * 60 + dt.minute
for hi, mi, hf, mf, intervalo, modo in HORARIOS:
@@ -62,14 +76,14 @@ def obtener_intervalo(dt: datetime) -> tuple[int, str] | None:
return (intervalo, modo)
return None
# ============================================================================
def segundos_hasta_proximo_inicio(dt: datetime) -> int:
target = dt.replace(hour=6, minute=30, second=0, microsecond=0)
if dt >= target:
target += timedelta(days=1)
return int((target - dt).total_seconds())
# ============================================================================
def segundos_hasta_proximo_dia_activo(dt: datetime) -> int:
for dias in range(1, 8):
prox = dt + timedelta(days=dias)
@@ -78,7 +92,7 @@ def segundos_hasta_proximo_dia_activo(dt: datetime) -> int:
return int((target - dt).total_seconds())
return 86400
# ============================================================================
def obtener_token():
"""Obtiene o renueva el token si es necesario."""
token = load_token()
@@ -111,7 +125,7 @@ def obtener_token():
print(" ⚠️ No se detectó token tras 30s. Continuando...")
return load_token()
# ============================================================================
def procesar_lote(token):
"""Procesa documentos pendientes desde HANA."""
print(f"\n📋 Buscando documentos pendientes en HANA...")
@@ -265,13 +279,13 @@ def procesar_lote(token):
for idx, doc in enumerate(docs_retry):
_procesar(doc, idx, len(docs_retry), es_retry=True)
# ============================================================================
def signal_handler(signum, frame):
global _running
print("\n\n⏹️ Señal de parada recibida. Deteniendo...")
_running = False
# ============================================================================
def main():
global _running
signal.signal(signal.SIGINT, signal_handler)
@@ -360,6 +374,7 @@ def main():
cerrar_conexion()
print("\n👋 Daemon detenido.")
# ============================================================================
if __name__ == "__main__":
main()
# ============================================================================