-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
42 additions
and
3 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,16 @@ | ||
import concurrent.futures | ||
from collections.abc import Callable | ||
from typing import TypeVar | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
def run_with_timeout(task: Callable[[], T], timeout: int) -> T: | ||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: | ||
future = executor.submit(task) | ||
try: | ||
# Wait at most 5 seconds for the function to complete | ||
result = future.result(timeout=timeout) | ||
return result | ||
except concurrent.futures.TimeoutError: | ||
raise TimeoutError(f"Function timed out after {timeout} seconds") |