Spaces:
Sleeping
Sleeping
| # worker.py | |
| import sys | |
| import time | |
| import sqlite3 | |
| import httpx | |
| import os | |
| import traceback | |
| # Args: site_id, db_file, ping_interval_seconds | |
| if len(sys.argv) < 4: | |
| print("Usage: python worker.py <site_id> <db_file> <ping_interval_seconds>") | |
| sys.exit(1) | |
| site_id = int(sys.argv[1]) | |
| DB_FILE = sys.argv[2] | |
| PING_INTERVAL_SECONDS = int(sys.argv[3]) | |
| def get_site_url(site_id): | |
| conn = sqlite3.connect(DB_FILE) | |
| cur = conn.cursor() | |
| cur.execute("SELECT url FROM sites WHERE id = ?", (site_id,)) | |
| row = cur.fetchone() | |
| conn.close() | |
| return row[0] if row else None | |
| def record_ping(site_id, status_code=None, latency_ms=None, error=None): | |
| conn = sqlite3.connect(DB_FILE) | |
| cur = conn.cursor() | |
| cur.execute(""" | |
| INSERT INTO pings (site_id, status_code, latency_ms, error) | |
| VALUES (?, ?, ?, ?) | |
| """, (site_id, status_code, latency_ms, error)) | |
| conn.commit() | |
| conn.close() | |
| def ping_once(url): | |
| try: | |
| start = time.time() | |
| with httpx.Client(timeout=30.0, follow_redirects=True) as client: | |
| r = client.get(url) | |
| latency = int((time.time() - start) * 1000) | |
| return r.status_code, latency, None | |
| except Exception as e: | |
| return None, None, str(e) | |
| def main_loop(): | |
| url = get_site_url(site_id) | |
| if not url: | |
| print("Site not found; exiting.") | |
| return | |
| print(f"Worker {site_id} started for {url}") | |
| while True: | |
| try: | |
| status_code, latency, error = ping_once(url) | |
| record_ping(site_id, status_code, latency, error) | |
| except Exception as e: | |
| print("Worker error:", e) | |
| traceback.print_exc() | |
| time.sleep(PING_INTERVAL_SECONDS) | |
| if __name__ == "__main__": | |
| main_loop() | |