Real-World Delay Examples
1. Rate Limiting API Requests
Controlled API Call Frequency
import time
import requests
def rate_limited_api_call(urls, delay=1):
results = []
for url in urls:
try:
response = requests.get(url)
results.append(response.json())
time.sleep(delay) ## Prevent overwhelming API
except requests.RequestException as e:
print(f"Error accessing {url}: {e}")
return results
urls = [
'https://api.example.com/endpoint1',
'https://api.example.com/endpoint2'
]
results = rate_limited_api_call(urls)
2. Retry Mechanism with Exponential Backoff
Intelligent Error Recovery
import time
def retry_with_backoff(func, max_retries=3):
for attempt in range(max_retries):
try:
return func()
except Exception as e:
wait_time = 2 ** attempt ## Exponential delay
print(f"Retry attempt {attempt + 1}, waiting {wait_time} seconds")
time.sleep(wait_time)
raise Exception("Max retries exceeded")
def unreliable_operation():
## Simulated unstable operation
import random
if random.random() < 0.7:
raise ValueError("Operation failed")
return "Success"
retry_with_backoff(unreliable_operation)
3. Periodic Task Scheduling
Background Task Execution
import threading
import time
class PeriodicTask:
def __init__(self, interval, function):
self.interval = interval
self.function = function
self.stop_event = threading.Event()
self.thread = threading.Thread(target=self._run)
def _run(self):
while not self.stop_event.is_set():
self.function()
time.sleep(self.interval)
def start(self):
self.thread.start()
def stop(self):
self.stop_event.set()
self.thread.join()
def monitor_system():
print("Checking system status for LabEx...")
## Run periodic task every 5 seconds
periodic_monitor = PeriodicTask(5, monitor_system)
periodic_monitor.start()
## Stop after 1 minute
time.sleep(60)
periodic_monitor.stop()
Delay Strategies Comparison
Scenario |
Delay Method |
Precision |
Use Case |
API Requests |
time.sleep() |
Second-level |
Rate Limiting |
Error Recovery |
Exponential Backoff |
Increasing |
Retry Mechanism |
Background Tasks |
threading.Timer() |
Configurable |
Periodic Execution |
Delay Method Selection Flowchart
graph TD
A[Delay Requirement] --> B{Type of Delay}
B -->|Consistent Interval| C[Periodic Task]
B -->|Error Recovery| D[Exponential Backoff]
B -->|Resource Management| E[Rate Limiting]
C --> F[Use Threading]
D --> G[Implement Retry Logic]
E --> H[Controlled Execution]
Advanced Considerations
- Implement proper error handling
- Use appropriate logging mechanisms
- Consider system resource constraints
- Balance between delay and performance