Practical Applications
Real-World Waiting Scenarios
Waiting techniques are essential in various programming contexts, from network operations to user interactions.
Common Application Categories
Category |
Use Case |
Typical Waiting Method |
Network Requests |
API Calls |
time.sleep() |
Rate Limiting |
API Restrictions |
Controlled Delays |
Retry Mechanisms |
Error Handling |
Exponential Backoff |
System Monitoring |
Resource Polling |
Periodic Checking |
1. Network Request Handling
import requests
import time
def robust_api_request(url, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.get(url)
response.raise_for_status()
return response
except requests.RequestException:
wait_time = 2 ** attempt ## Exponential backoff
time.sleep(wait_time)
raise Exception("API request failed")
Retry Strategy Visualization
graph TD
A[Initial Request] --> B{Request Successful?}
B -->|No| C[Wait and Retry]
C --> D[Increase Wait Time]
D --> E[Retry Limit Reached?]
E -->|No| B
E -->|Yes| F[Raise Exception]
2. Rate Limiting Implementation
import time
from functools import wraps
def rate_limit(max_per_minute):
min_interval = 60.0 / max_per_minute
def decorator(func):
last_time_called = [0.0]
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_time_called[0]
left_to_wait = min_interval - elapsed
if left_to_wait > 0:
time.sleep(left_to_wait)
result = func(*args, **kwargs)
last_time_called[0] = time.time()
return result
return wrapper
return decorator
@rate_limit(max_per_minute=5)
def api_call(data):
print(f"Processing {data}")
3. Periodic System Monitoring
import time
import psutil
def monitor_system_resources(interval=5, duration=60):
start_time = time.time()
while time.time() - start_time < duration:
cpu_usage = psutil.cpu_percent()
memory_usage = psutil.virtual_memory().percent
print(f"CPU: {cpu_usage}%, Memory: {memory_usage}%")
time.sleep(interval)
Asynchronous Waiting Approach
import asyncio
async def async_task_queue(tasks, max_concurrent=3):
semaphore = asyncio.Semaphore(max_concurrent)
async def bounded_task(task):
async with semaphore:
return await task
return await asyncio.gather(*(bounded_task(task) for task in tasks))
LabEx Recommendation
LabEx suggests practicing these techniques in controlled environments to understand their nuanced applications in real-world scenarios.
Key Takeaways
- Implement intelligent waiting strategies
- Balance between responsiveness and resource efficiency
- Choose appropriate waiting mechanism for specific use case
- Consider both synchronous and asynchronous approaches