1717from typing import TYPE_CHECKING , Any , Optional
1818import requests
1919import threading
20- import time
2120from requests import codes as http_status_codes
2221from requests import exceptions as requests_exceptions
2322
@@ -216,8 +215,8 @@ def __init__(
216215 self .set_update_interval (update_interval )
217216 self .set_blocking_timeout (blocking_timeout )
218217 self .last_modified : Optional [str ] = None
219- self ._polling_thread = threading .Thread ( target = self . _run )
220- self ._polling_thread . daemon = True
218+ self .stopped = threading .Event ( )
219+ self ._initialize_thread ()
221220 self ._polling_thread .start ()
222221
223222 @staticmethod
@@ -375,15 +374,23 @@ def is_running(self) -> bool:
375374 """ Check if polling thread is alive or not. """
376375 return self ._polling_thread .is_alive ()
377376
377+ def stop (self ) -> None :
378+ """ Stop the polling thread and wait for it to exit. """
379+ if self .is_running :
380+ self .stopped .set ()
381+ self ._polling_thread .join ()
382+
378383 def _run (self ) -> None :
379384 """ Triggered as part of the thread which fetches the datafile and sleeps until next update interval. """
380385 try :
381- while self . is_running :
386+ while True :
382387 self .fetch_datafile ()
383- time .sleep (self .update_interval )
388+ if self .stopped .wait (self .update_interval ):
389+ self .stopped .clear ()
390+ break
384391 except (OSError , OverflowError ) as err :
385392 self .logger .error (
386- f'Error in time.sleep. Provided update_interval value may be too big. Error: { err } '
393+ f'Provided update_interval value may be too big. Error: { err } '
387394 )
388395 raise
389396
@@ -392,6 +399,9 @@ def start(self) -> None:
392399 if not self .is_running :
393400 self ._polling_thread .start ()
394401
402+ def _initialize_thread (self ) -> None :
403+ self ._polling_thread = threading .Thread (target = self ._run , daemon = True )
404+
395405
396406class AuthDatafilePollingConfigManager (PollingConfigManager ):
397407 """ Config manager that polls for authenticated datafile using access token. """
0 commit comments