1. import json
  2. import time
  3. def sort_maintenance_records(json_data, timeout=10):
  4. """
  5. Sorts records of JSON responses for maintenance tasks with a timeout.
  6. Args:
  7. json_data (str): A JSON string containing a list of maintenance records.
  8. timeout (int): Timeout in seconds for processing each record.
  9. Returns:
  10. list: A sorted list of maintenance records. Returns an empty list if an error occurs.
  11. """
  12. try:
  13. records = json.loads(json_data)
  14. if not isinstance(records, list):
  15. print("Error: JSON data must be a list.")
  16. return []
  17. def process_record(record):
  18. """Simulates processing a maintenance record with a timeout."""
  19. try:
  20. # Simulate some work
  21. time.sleep(0.1)
  22. return record
  23. except Exception as e:
  24. print(f"Error processing record: {e}")
  25. return None # Or handle the error differently (e.g., log)
  26. sorted_records = sorted(records, key=process_record, reverse=True) #Sort records
  27. # Filter out None values returned by process_record (records that failed)
  28. sorted_records = [record for record in sorted_records if record is not None]
  29. return sorted_records
  30. except json.JSONDecodeError as e:
  31. print(f"Error decoding JSON: {e}")
  32. return []
  33. except Exception as e:
  34. print(f"An unexpected error occurred: {e}")
  35. return []

Add your comment