import json
import time
import datetime
def export_user_data(user_data, filename="user_data.json", retry_interval=60):
"""
Exports user data to a JSON file with retry mechanism.
Args:
user_data (list): A list of dictionaries, where each dictionary represents user data.
filename (str): The name of the file to export to. Defaults to "user_data.json".
retry_interval (int): Retry interval in seconds. Defaults to 60.
"""
max_retries = 3 #Limit the number of retries
for attempt in range(max_retries):
try:
with open(filename, 'w') as f:
json.dump(user_data, f, indent=4) # Write the data to the file with indentation
print(f"Successfully exported data to {filename}")
return # Exit the function if successful
except Exception as e:
print(f"Export failed on attempt {attempt+1}: {e}")
if attempt < max_retries - 1:
print(f"Retrying in {retry_interval} seconds...")
time.sleep(retry_interval)
else:
print("Export failed after multiple retries.")
if __name__ == '__main__':
# Example usage:
sample_user_data = [
{"user_id": 1, "name": "Alice", "email": "alice@example.com"},
{"user_id": 2, "name": "Bob", "email": "bob@example.com"}
]
export_user_data(sample_user_data, "my_user_data.json", 30)
# Simulate data update and export again
time.sleep(5)
updated_user_data = sample_user_data + [{"user_id": 3, "name":"Charlie", "email":"charlie@example.com"}]
export_user_data(updated_user_data, "updated_user_data.json", 60)
Add your comment