# run_scheduler.py import asyncio import logging import threading import time import schedule from datetime import datetime, timedelta, timezone from database.manager import get_session logger = logging.getLogger(__name__) # ICAIM completion callback — decision_tracker service reserved for future implementation def on_icaim_task_complete(plan_id: int, sku: str): """Triggered by ICAIM scheduler after task completion.""" logger.info("[Scheduler] [ICAIM] on_icaim_task_complete: plan_id=%s sku=%s", plan_id, sku) # schedule settings (keep original schedule logic) def run_icaim_task(): """Simulate ICAIM task execution.""" logger.info("[Scheduler] [ICAIM] executing ICAIM analysis task...") plan_id = 123 sku = "sample_sku" on_icaim_task_complete(plan_id, sku) logger.info("[Scheduler] [ICAIM] task completed, triggered follow_up schedule") schedule.every(6).hours.do(run_icaim_task) logger.info("📅 scheduled: ICAIM analysis task every 6 hours") # B8 FIX: Elephant Alpha autonomous engine startup # Runs in a dedicated daemon thread with its own asyncio event loop. # Isolated from the schedule loop so a crash doesn't kill the scheduler. def _run_elephant_alpha_engine(): """Daemon thread: runs EA autonomous monitoring in its own asyncio loop.""" try: from services.elephant_alpha_autonomous_engine import autonomous_engine loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) logger.info("🐘 [ElephantAlpha] Autonomous engine thread started") loop.run_until_complete(autonomous_engine.start_autonomous_monitoring()) except Exception as e: logger.error(f"🐘 [ElephantAlpha] Engine crashed: {e}") finally: loop.close() _ea_thread = threading.Thread( target=_run_elephant_alpha_engine, daemon=True, name="elephant-alpha-engine" ) _ea_thread.start() logger.info("🐘 [ElephantAlpha] Autonomous engine thread launched") # start schedule loop (keep original main loop) if __name__ == "__main__": logger.info("Scheduler started.") while True: try: schedule.run_pending() time.sleep(1) except KeyboardInterrupt: logger.info("Scheduler stopped.") break except Exception as e: logger.error(f"Scheduler error: {e}") time.sleep(5)