1. import time
  2. import json
  3. import threading
  4. class TimestampConfig:
  5. def __init__(self, config_file="config.json", timeout=5):
  6. self.config_file = config_file
  7. self.timeout = timeout
  8. self.config = self._load_config()
  9. self.lock = threading.Lock() # For thread-safe access
  10. def _load_config(self):
  11. """Loads timestamp configuration from a JSON file."""
  12. try:
  13. with open(self.config_file, "r") as f:
  14. config = json.load(f)
  15. return config
  16. except FileNotFoundError:
  17. print(f"Error: Configuration file '{self.config_file}' not found.")
  18. return {}
  19. except json.JSONDecodeError:
  20. print(f"Error: Invalid JSON format in '{self.config_file}'.")
  21. return {}
  22. def get_timestamp(self, key):
  23. """Retrieves a timestamp value from the configuration with a timeout."""
  24. with self.lock: # Ensure thread-safe access to config
  25. if key in self.config:
  26. return self.config[key]
  27. else:
  28. print(f"Error: Key '{key}' not found in configuration.")
  29. return None
  30. def validate_config(self):
  31. """Validates the config and returns True/False"""
  32. with self.lock:
  33. if not isinstance(self.config, dict):
  34. print("Error: Configuration is not a dictionary.")
  35. return False
  36. for key, value in self.config.items():
  37. if not isinstance(value, (int, float)):
  38. print(f"Error: Value for key '{key}' is not a number.")
  39. return False
  40. return True
  41. def check_timeout(self, key):
  42. """Checks if a timestamp is within the timeout period."""
  43. with self.lock:
  44. if key in self.config:
  45. timestamp = self.config[key]
  46. if isinstance(timestamp, float):
  47. if time.time() - timestamp > self.timeout:
  48. return False
  49. else:
  50. print(f"Error: Timestamp for '{key}' is not a number")
  51. return False
  52. else:
  53. print(f"Error: Key '{key}' not found in configuration.")
  54. return False
  55. return True
  56. if __name__ == '__main__':
  57. # Example Usage (create a config.json file first)
  58. config = TimestampConfig()
  59. # Example configuration (config.json)
  60. """
  61. {
  62. "start_time": 1678886400.0,
  63. "timeout_seconds": 60
  64. }
  65. """
  66. if config.validate_config():
  67. start_time = config.get_timestamp("start_time")
  68. timeout_seconds = config.get_timestamp("timeout_seconds")
  69. if start_time is not None and timeout_seconds is not None:
  70. print(f"Start Time: {start_time}")
  71. print(f"Timeout: {timeout_seconds} seconds")
  72. if config.check_timeout("start_time"):
  73. print("Timestamp is within the timeout period.")
  74. else:
  75. print("Timestamp is outside the timeout period.")
  76. else:
  77. print("Configuration is invalid. Exiting.")

Add your comment