Practical Scenarios
Real-World Time Delay Applications
1. Web Scraping Rate Limiting
Implement delays to prevent overwhelming web servers and avoid IP blocking:
import time
import requests
def controlled_web_scraping():
urls = ['https://example1.com', 'https://example2.com', 'https://example3.com']
for url in urls:
try:
response = requests.get(url)
print(f"Scraping {url}")
## Delay between requests to avoid rate limiting
time.sleep(2) ## 2-second delay between requests
except requests.RequestException as e:
print(f"Error scraping {url}: {e}")
2. Retry Mechanism with Exponential Backoff
graph TD
A[Initial Attempt] --> B{Success?}
B -->|No| C[Wait and Retry]
C --> D[Increase Delay]
D --> E[Retry Again]
E --> B
Implement a robust retry strategy with progressive delays:
import time
def robust_network_request(max_retries=5):
retry_delay = 1
for attempt in range(max_retries):
try:
## Simulated network request
result = perform_network_operation()
return result
except Exception as e:
print(f"Attempt {attempt + 1} failed. Retrying...")
time.sleep(retry_delay)
retry_delay *= 2 ## Exponential backoff
raise Exception("Maximum retries exceeded")
3. Periodic Task Scheduling
Scenario |
Delay Strategy |
Use Case |
System Monitoring |
Fixed Interval |
Check system resources |
Data Collection |
Adaptive Delay |
Gather metrics periodically |
User Interaction |
Dynamic Timing |
Create responsive interfaces |
import time
import psutil
def system_health_monitor():
while True:
## Check CPU and memory usage
cpu_usage = psutil.cpu_percent()
memory_usage = psutil.virtual_memory().percent
print(f"CPU: {cpu_usage}%, Memory: {memory_usage}%")
## Delay between monitoring cycles
time.sleep(5) ## Check every 5 seconds
def simulate_user_typing(message):
for char in message:
print(char, end='', flush=True)
time.sleep(0.1) ## Simulate typing speed
print()
simulate_user_typing("Welcome to LabEx Python Tutorial!")
5. Asynchronous Progress Indication
import asyncio
async def long_running_task():
print("Task started")
await asyncio.sleep(3) ## Simulate long processing
print("Task completed")
async def progress_indicator():
while True:
print("Processing...", flush=True)
await asyncio.sleep(1)
async def main():
task = asyncio.create_task(long_running_task())
indicator = asyncio.create_task(progress_indicator())
await task
indicator.cancel()
## Run the async main function
asyncio.run(main())
Key Takeaways
- Time delays are versatile tools for managing program execution
- Choose appropriate delay strategies based on specific requirements
- Balance between responsiveness and resource efficiency
- Consider asynchronous approaches for non-blocking operations
By understanding these practical scenarios, developers can effectively implement time delays in various Python applications with LabEx's recommended techniques.