1. import time
  2. import random
  3. def retry_record_operation(record, operation, max_retries=3, retry_delay=2):
  4. """
  5. Retries an operation on a user record with fallback logic.
  6. Args:
  7. record: The user record (can be any data structure).
  8. operation: A function that performs the operation on the record.
  9. max_retries: The maximum number of retry attempts.
  10. retry_delay: The delay (in seconds) between retries.
  11. Returns:
  12. The result of the operation if successful, otherwise None.
  13. """
  14. for attempt in range(max_retries):
  15. try:
  16. result = operation(record) # Execute the operation
  17. print(f"Operation successful on attempt {attempt + 1}")
  18. return result # Return the result if successful
  19. except Exception as e:
  20. print(f"Operation failed on attempt {attempt + 1}: {e}")
  21. if attempt < max_retries - 1:
  22. print(f"Retrying in {retry_delay} seconds...")
  23. time.sleep(retry_delay + random.uniform(0, 1)) # Add a little randomness
  24. else:
  25. print("Max retries reached. Operation failed.")
  26. # Fallback logic - handle the failure gracefully
  27. print("Falling back to default value/alternative action.")
  28. return None # or some default value/action
  29. def example_operation(record):
  30. """
  31. Example operation that might fail (e.g., network call).
  32. """
  33. if random.random() < 0.5: # Simulate a 50% chance of failure
  34. raise ValueError("Simulated error during operation.")
  35. else:
  36. return f"Operation successful for {record}"
  37. if __name__ == '__main__':
  38. # Example usage
  39. user_record = {"user_id": 123, "name": "John Doe"}
  40. operation_result = retry_record_operation(user_record, example_operation)
  41. if operation_result:
  42. print(f"Final result: {operation_result}")
  43. else:
  44. print("Operation failed after multiple retries.")

Add your comment