import time
import json
import threading
class TimestampConfig:
def __init__(self, config_file="config.json", timeout=5):
self.config_file = config_file
self.timeout = timeout
self.config = self._load_config()
self.lock = threading.Lock() # For thread-safe access
def _load_config(self):
"""Loads timestamp configuration from a JSON file."""
try:
with open(self.config_file, "r") as f:
config = json.load(f)
return config
except FileNotFoundError:
print(f"Error: Configuration file '{self.config_file}' not found.")
return {}
except json.JSONDecodeError:
print(f"Error: Invalid JSON format in '{self.config_file}'.")
return {}
def get_timestamp(self, key):
"""Retrieves a timestamp value from the configuration with a timeout."""
with self.lock: # Ensure thread-safe access to config
if key in self.config:
return self.config[key]
else:
print(f"Error: Key '{key}' not found in configuration.")
return None
def validate_config(self):
"""Validates the config and returns True/False"""
with self.lock:
if not isinstance(self.config, dict):
print("Error: Configuration is not a dictionary.")
return False
for key, value in self.config.items():
if not isinstance(value, (int, float)):
print(f"Error: Value for key '{key}' is not a number.")
return False
return True
def check_timeout(self, key):
"""Checks if a timestamp is within the timeout period."""
with self.lock:
if key in self.config:
timestamp = self.config[key]
if isinstance(timestamp, float):
if time.time() - timestamp > self.timeout:
return False
else:
print(f"Error: Timestamp for '{key}' is not a number")
return False
else:
print(f"Error: Key '{key}' not found in configuration.")
return False
return True
if __name__ == '__main__':
# Example Usage (create a config.json file first)
config = TimestampConfig()
# Example configuration (config.json)
"""
{
"start_time": 1678886400.0,
"timeout_seconds": 60
}
"""
if config.validate_config():
start_time = config.get_timestamp("start_time")
timeout_seconds = config.get_timestamp("timeout_seconds")
if start_time is not None and timeout_seconds is not None:
print(f"Start Time: {start_time}")
print(f"Timeout: {timeout_seconds} seconds")
if config.check_timeout("start_time"):
print("Timestamp is within the timeout period.")
else:
print("Timestamp is outside the timeout period.")
else:
print("Configuration is invalid. Exiting.")
Add your comment