File size: 1,631 Bytes
25ae7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Keep-Alive Service to prevent Render.com from sleeping
Pings the server every 10 minutes to maintain activity
"""
import asyncio
import httpx
import logging
from datetime import datetime

logger = logging.getLogger("keep_alive")

class KeepAliveService:
    def __init__(self, base_url: str = "http://localhost:7860"):
        self.base_url = base_url
        self.running = False
        self.ping_interval = 600  # 10 minutes
        
    async def start(self):
        """Start the keep-alive service"""
        self.running = True
        logger.info("🔄 Keep-Alive service started (pinging every 10 minutes)")
        
        while self.running:
            try:
                await asyncio.sleep(self.ping_interval)
                await self._ping()
            except Exception as e:
                logger.error(f"Keep-Alive error: {e}")
    
    async def _ping(self):
        """Send a ping to keep the service alive"""
        try:
            async with httpx.AsyncClient(timeout=10.0) as client:
                response = await client.get(f"{self.base_url}/health")
                if response.status_code == 200:
                    logger.info(f"✅ Keep-Alive ping successful at {datetime.now().strftime('%H:%M:%S')}")
                else:
                    logger.warning(f"⚠️ Keep-Alive ping returned {response.status_code}")
        except Exception as e:
            logger.warning(f"Keep-Alive ping failed: {e}")
    
    def stop(self):
        """Stop the keep-alive service"""
        self.running = False
        logger.info("Keep-Alive service stopped")

keep_alive = KeepAliveService()