Skip to content

Commit 5709b25

Browse files
authored
fix: shut down "session flusher" more promptly (#4561)
Currently this thread will wait for `sleep(self.flush_interval)` to end before checking `self._running`. We can do better by using an Event. Now it will wait for `self.flush_interval` or until `self.__shutdown_requested` is set, whichever is shorter.
1 parent a7b2d67 commit 5709b25

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

sentry_sdk/sessions.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import os
2-
import time
32
import warnings
4-
from threading import Thread, Lock
3+
from threading import Thread, Lock, Event
54
from contextlib import contextmanager
65

76
import sentry_sdk
@@ -162,7 +161,7 @@ def __init__(
162161
self._thread_lock = Lock()
163162
self._aggregate_lock = Lock()
164163
self._thread_for_pid = None # type: Optional[int]
165-
self._running = True
164+
self.__shutdown_requested = Event()
166165

167166
def flush(self):
168167
# type: (...) -> None
@@ -208,10 +207,10 @@ def _ensure_running(self):
208207

209208
def _thread():
210209
# type: (...) -> None
211-
while self._running:
212-
time.sleep(self.flush_interval)
213-
if self._running:
214-
self.flush()
210+
running = True
211+
while running:
212+
running = not self.__shutdown_requested.wait(self.flush_interval)
213+
self.flush()
215214

216215
thread = Thread(target=_thread)
217216
thread.daemon = True
@@ -220,7 +219,7 @@ def _thread():
220219
except RuntimeError:
221220
# Unfortunately at this point the interpreter is in a state that no
222221
# longer allows us to spawn a thread and we have to bail.
223-
self._running = False
222+
self.__shutdown_requested.set()
224223
return None
225224

226225
self._thread = thread
@@ -271,7 +270,7 @@ def add_session(
271270

272271
def kill(self):
273272
# type: (...) -> None
274-
self._running = False
273+
self.__shutdown_requested.set()
275274

276275
def __del__(self):
277276
# type: (...) -> None

0 commit comments

Comments
 (0)