Always-On Agent Design Patterns
Background processes, daemon agents, and persistent connection management.
What Is an Always-On Agent?
An always-on agent runs continuously as a background service, waiting for events and taking action proactively. Unlike request-response agents, it persists between interactions and maintains state over time.
Daemon Process Pattern
A daemon process runs in the background, independent of any terminal session. Use Python's daemon threads or a process supervisor to keep the agent running after the terminal closes.
import threading
import time
import signal
import sys
shutdown_flag = threading.Event()
def agent_main_loop():
print('Agent daemon started')
while not shutdown_flag.is_set():
try:
# Agent work: check for events, process tasks
perform_agent_cycle()
shutdown_flag.wait(timeout=60) # Sleep 60s, wakes on shutdown
except Exception as e:
print(f'Agent loop error: {e}')
shutdown_flag.wait(timeout=5) # Brief pause on error
print('Agent daemon stopped')
def perform_agent_cycle():
print(f'Agent cycle at {time.strftime("%H:%M:%S")}')
# Check emails, process queue, run scheduled tasks
def handle_signal(signum, frame):
print(f'Signal {signum} received, shutting down...')
shutdown_flag.set()
# Register signal handlers for graceful shutdown
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
# Start as daemon thread
thread = threading.Thread(target=agent_main_loop, daemon=True)
thread.start()
print('Agent running in background')All lessons in this course
- Always-On Agent Design Patterns
- Proactive Notification and Alert Systems
- Context Persistence Across Sessions
- Building a Daily Briefing Agent