-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Generalizes timeout, applies it also to single sample computation.
- Loading branch information
1 parent
5b895c6
commit 0082d49
Showing
3 changed files
with
73 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
"""General-purpose one-time timeout functionality based on Unix signal alarm.""" | ||
from typing import Callable | ||
import signal | ||
|
||
from spatialprofilingtoolbox.db.database_connection import DBCursor | ||
from spatialprofilingtoolbox.standalone_utilities.log_formats import colorized_logger | ||
|
||
logger = colorized_logger(__name__) | ||
|
||
|
||
TIMEOUT_SECONDS_DEFAULT = 300 | ||
|
||
|
||
class SPTTimeoutError(RuntimeError): | ||
def __init__(self, message: str): | ||
super().__init__(message) | ||
self.message = message | ||
|
||
|
||
class TimeoutHandler: | ||
active: bool | ||
callback: Callable | ||
timeout: int | ||
|
||
def __init__(self, callback: Callable, timeout: int): | ||
self.active = True | ||
self.callback = callback | ||
self.timeout = timeout | ||
|
||
def handle(self, signum, frame) -> None: | ||
if self.active: | ||
message = f'Waited {self.timeout} seconds, timed out.' | ||
logger.error(message) | ||
self.callback() | ||
raise TimeoutError(message) | ||
|
||
def disalarm(self) -> None: | ||
self.active = False | ||
|
||
|
||
def create_timeout_handler(callback: Callable, timeout_seconds: int = TIMEOUT_SECONDS_DEFAULT) -> TimeoutHandler: | ||
handler = TimeoutHandler(callback, timeout_seconds) | ||
signal.signal(signal.SIGALRM, handler.handle) | ||
signal.alarm(timeout_seconds) | ||
return handler |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters