import time
import random
def retry_record_operation(record, operation, max_retries=3, retry_delay=2):
"""
Retries an operation on a user record with fallback logic.
Args:
record: The user record (can be any data structure).
operation: A function that performs the operation on the record.
max_retries: The maximum number of retry attempts.
retry_delay: The delay (in seconds) between retries.
Returns:
The result of the operation if successful, otherwise None.
"""
for attempt in range(max_retries):
try:
result = operation(record) # Execute the operation
print(f"Operation successful on attempt {attempt + 1}")
return result # Return the result if successful
except Exception as e:
print(f"Operation failed on attempt {attempt + 1}: {e}")
if attempt < max_retries - 1:
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay + random.uniform(0, 1)) # Add a little randomness
else:
print("Max retries reached. Operation failed.")
# Fallback logic - handle the failure gracefully
print("Falling back to default value/alternative action.")
return None # or some default value/action
def example_operation(record):
"""
Example operation that might fail (e.g., network call).
"""
if random.random() < 0.5: # Simulate a 50% chance of failure
raise ValueError("Simulated error during operation.")
else:
return f"Operation successful for {record}"
if __name__ == '__main__':
# Example usage
user_record = {"user_id": 123, "name": "John Doe"}
operation_result = retry_record_operation(user_record, example_operation)
if operation_result:
print(f"Final result: {operation_result}")
else:
print("Operation failed after multiple retries.")
Add your comment