|
1 | 1 | import atexit
|
2 | 2 | import logging
|
3 | 3 | import threading
|
| 4 | +import time |
4 | 5 | import warnings
|
5 | 6 | from abc import abstractmethod
|
6 | 7 | from datetime import timedelta
|
@@ -37,6 +38,8 @@ def __init__(self, project: str, cache_ttl_seconds: int, cache_mode: str):
|
37 | 38 | )
|
38 | 39 | self.cached_registry_proto = self.proto()
|
39 | 40 | self.cached_registry_proto_created = _utc_now()
|
| 41 | + self._stop_event = threading.Event() |
| 42 | + logger.info(f"Registry initialized with cache mode: {cache_mode}") |
40 | 43 | if cache_mode == "thread":
|
41 | 44 | self._start_thread_async_refresh(cache_ttl_seconds)
|
42 | 45 | atexit.register(self._exit_handler)
|
@@ -458,12 +461,29 @@ def _refresh_cached_registry_if_necessary(self):
|
458 | 461 | def _start_thread_async_refresh(self, cache_ttl_seconds):
|
459 | 462 | self.refresh()
|
460 | 463 | if cache_ttl_seconds <= 0:
|
| 464 | + logger.info("Registry cache refresh thread not started as TTL is 0") |
461 | 465 | return
|
462 |
| - self.registry_refresh_thread = threading.Timer( |
463 |
| - cache_ttl_seconds, self._start_thread_async_refresh, [cache_ttl_seconds] |
464 |
| - ) |
465 |
| - self.registry_refresh_thread.daemon = True |
466 |
| - self.registry_refresh_thread.start() |
| 466 | + |
| 467 | + def refresh_loop(): |
| 468 | + while not self._stop_event.is_set(): |
| 469 | + try: |
| 470 | + time.sleep(cache_ttl_seconds) |
| 471 | + if not self._stop_event.is_set(): |
| 472 | + self.refresh() |
| 473 | + except Exception as e: |
| 474 | + logger.exception("Exception in refresh_loop: %s", e) |
| 475 | + |
| 476 | + try: |
| 477 | + self.registry_refresh_thread = threading.Thread( |
| 478 | + target=refresh_loop, daemon=True |
| 479 | + ) |
| 480 | + self.registry_refresh_thread.start() |
| 481 | + logger.info( |
| 482 | + f"Registry cache refresh thread started with TTL {cache_ttl_seconds}" |
| 483 | + ) |
| 484 | + except Exception as e: |
| 485 | + logger.exception("Failed to start registry refresh thread: %s", e) |
467 | 486 |
|
468 | 487 | def _exit_handler(self):
|
469 |
| - self.registry_refresh_thread.cancel() |
| 488 | + logger.info("Exiting, setting stop event for registry cache refresh thread") |
| 489 | + self._stop_event.set() |
0 commit comments