Actualizar backend/cache_manager.py

This commit is contained in:
2026-08-31 14:28:30 -05:00
parent 9a73e95ae5
commit b4d5c790d8

View File

@@ -6,7 +6,7 @@ from typing import Any, Callable, Dict, Tuple
_CACHE: Dict[str, Tuple[float, Any]] = {} _CACHE: Dict[str, Tuple[float, Any]] = {}
_LOCK = threading.Lock() _LOCK = threading.Lock()
_DEFAULT_TTL = 900 # 15 min _DEFAULT_TTL = 1800 # 30 min
def _make_key(prefix: str, args: tuple) -> str: def _make_key(prefix: str, args: tuple) -> str:
@@ -60,20 +60,40 @@ def cache_stats() -> dict:
_background_started = False _background_started = False
def start_background_refresh(refresh_fn: Callable[[], None], interval: int = 900): def _en_horario_refresco(ahora):
"""Reglas de auto-refresco (hora local del servidor):
- Madrugada (antes de 07:30 o desde 22:30): NO (solo manual).
- Domingo: solo de 08:00 a 14:00.
- Lun-Sab: de 07:30 a 22:30."""
minutos = ahora.hour * 60 + ahora.minute
dow = ahora.weekday() # 0=lunes ... 6=domingo
if dow == 6: # domingo: 08:00 - 14:00
return 8 * 60 <= minutos < 14 * 60
return 7 * 60 + 30 <= minutos < 22 * 60 + 30 # lun-sab: 07:30 - 22:30
def start_background_refresh(refresh_fn: Callable[[], None], interval: int = 1800):
global _background_started global _background_started
if _background_started: if _background_started:
return return
_background_started = True _background_started = True
def _loop(): def _loop():
from datetime import datetime
ultimo = 0.0
while True: while True:
time.sleep(interval) time.sleep(60) # chequear cada minuto para respetar los horarios
ahora = datetime.now()
if not _en_horario_refresco(ahora):
continue # fuera de horario -> no auto-refresca
if (time.time() - ultimo) < interval:
continue # aún no pasan 'interval' seg desde el último
try: try:
refresh_fn() refresh_fn()
ultimo = time.time()
except Exception as e: except Exception as e:
print(f"[background refresh] error: {e}") print(f"[background refresh] error: {e}")
t = threading.Thread(target=_loop, daemon=True) t = threading.Thread(target=_loop, daemon=True)
t.start() t.start()
print(f"[cache] refresco en segundo plano cada {interval}s iniciado") print(f"[cache] refresco en segundo plano cada {interval}s (con horario) iniciado")