1. import time
  2. import datetime
  3. import random
  4. import logging
  5. logging.basicConfig(level=logging.INFO)
  6. def guarded_timestamp(func, retries=3, delay=5):
  7. """
  8. Guards execution of a timestamp-related function with retry logic.
  9. Args:
  10. func: The function that generates the timestamp.
  11. retries: The number of retry attempts.
  12. delay: The delay between retries in seconds.
  13. Returns:
  14. The timestamp generated by the function, or None if all retries fail.
  15. """
  16. for attempt in range(retries):
  17. try:
  18. timestamp = func() # Execute the timestamp function
  19. return timestamp
  20. except Exception as e:
  21. logging.warning(f"Timestamp generation failed (attempt {attempt + 1}/{retries}): {e}")
  22. if attempt < retries - 1:
  23. time.sleep(delay + random.uniform(0, delay/2)) # Add jitter to delay
  24. else:
  25. logging.error(f"Timestamp generation failed after {retries} attempts.")
  26. return None # Return None if all retries fail
  27. def get_current_timestamp():
  28. """
  29. Gets the current timestamp. Simulates a potentially flaky operation.
  30. """
  31. # Simulate a flaky operation (e.g., network latency)
  32. if random.random() < 0.2: # 20% chance of failure
  33. raise Exception("Simulated timestamp generation failure")
  34. return datetime.datetime.now().timestamp()
  35. if __name__ == '__main__':
  36. timestamp = guarded_timestamp(get_current_timestamp)
  37. if timestamp:
  38. print(f"Generated timestamp: {timestamp}")
  39. else:
  40. print("Failed to generate timestamp after multiple retries.")

Add your comment