-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathexecutor.py
More file actions
49 lines (40 loc) · 1.67 KB
/
executor.py
File metadata and controls
49 lines (40 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from datetime import datetime, timezone
from abc import ABC, abstractmethod
from typing import Callable, Awaitable, Any
from .execution_result import ExecutionResult
class Executor(ABC):
"""Protocol for executing asynchronous functions concurrently."""
async def run_func(
self, exe_id: int, func: Callable[[], Awaitable[Any]]
) -> ExecutionResult:
"""Run the given asynchronous function.
:param exe_id: An identifier for the execution instance.
:param func: An asynchronous function to be executed.
"""
start_time = datetime.now(timezone.utc).timestamp()
try:
result = await func()
return ExecutionResult(
exe_id=exe_id,
result=result,
start_time=start_time,
end_time=datetime.now(timezone.utc).timestamp(),
)
except Exception as e: # pylint: disable=broad-except
return ExecutionResult(
exe_id=exe_id,
error=e,
start_time=start_time,
end_time=datetime.now(timezone.utc).timestamp(),
)
@abstractmethod
def run(
self, func: Callable[[], Awaitable[Any]], num_workers: int = 1
) -> list[ExecutionResult]:
"""Run the given asynchronous function using the specified number of workers.
:param func: An asynchronous function to be executed.
:param num_workers: The number of concurrent workers to use.
"""
raise NotImplementedError("This method should be implemented by subclasses.")