unknown 1 mese fa
parent
commit
c0f936e6fa

+ 51 - 0
python_net/asyncio/cansel.py

@@ -0,0 +1,51 @@
+import asyncio
+from asyncio import CancelledError
+from util import delay
+
+
+async def test_1():
+    """Отмена задачи"""
+    long_task = asyncio.create_task(delay(10))
+    seconds_elapsed = 0
+
+    while not long_task.done():
+        print('Задача не закончилась, следующая проверка через секунду.')
+        await asyncio.sleep(1)
+        seconds_elapsed = seconds_elapsed + 1
+        if seconds_elapsed == 5:
+            long_task.cancel()
+
+    try:
+        await long_task
+    except CancelledError:
+        print('Наша задача была снята')
+
+
+async def test_2():
+    """timout"""
+    delay_task = asyncio.create_task(delay(2))
+    try:
+        result = await asyncio.wait_for(delay_task, timeout=1)
+        print(result)
+    except asyncio.exceptions.TimeoutError:
+        print('Timeout!')
+        print(f'Задача была снята? {delay_task.cancelled()}')
+
+
+async def test_3():
+    task = asyncio.create_task(delay(10))
+
+    try:
+        result = await asyncio.wait_for(asyncio.shield(task), 5)
+        print(result)
+    except TimeoutError:
+        print("Задача заняла более 5 с, скоро она закончится!")
+        result = await task
+        print(result)
+    
+
+
+if __name__ == '__main__':
+    # asyncio.run(test_1())
+    # asyncio.run(test_2())
+    asyncio.run(test_3())

+ 39 - 0
python_net/asyncio/future.py

@@ -0,0 +1,39 @@
+from asyncio import Future
+import asyncio
+
+
+def test_1():
+    my_future = Future()
+    print(f'my_future готов? {my_future.done()}')
+    my_future.set_result(42)
+    print(f'my_future готов? {my_future.done()}')
+    print(f'Какой результат хранится в my_future? {my_future.result()}')
+
+
+def make_request() -> Future:
+    future = Future()
+    asyncio.create_task(set_future_value(future))
+    return future
+
+
+async def set_future_value(future) -> None:
+    await asyncio.sleep(1)
+    future.set_result(42)
+
+
+async def test_2():
+    future = make_request()
+    print(f'my_future готов? {future.done()}')
+    value = await future
+    print(f'my_future готов? {future.done()}')
+    print(value)
+
+
+
+async def main():
+    # test_1()
+    test_2()
+
+
+if __name__ == '__main__':
+    asyncio.run(test_2())

+ 22 - 0
python_net/asyncio/misc.py

@@ -0,0 +1,22 @@
+import asyncio
+from util import async_timed
+
+
+@async_timed()
+async def delay(delay_seconds: int) -> int:
+    print(f'засыпаю на {delay_seconds} с')
+    await asyncio.sleep(delay_seconds)
+    print(f'сон в течение {delay_seconds} с закончился')
+    return delay_seconds
+
+
+@async_timed()
+async def main():
+    task_one = asyncio.create_task(delay(2))
+    task_two = asyncio.create_task(delay(3))
+
+    await task_one
+    await task_two
+
+
+asyncio.run(main())

+ 2 - 1
python_net/asyncio/util/__init__.py

@@ -1 +1,2 @@
-from util.delay_functions import delay
+from util.delay_functions import delay
+from util.async_timer import async_timed

+ 20 - 0
python_net/asyncio/util/async_timer.py

@@ -0,0 +1,20 @@
+from functools import wraps
+import time
+from typing import Callable, Any
+
+
+def async_timed():
+    def wrapper(func: Callable) -> Callable:
+        @wraps(func)
+        async def wrapped(*args, **kwargs) -> Any:
+            # print(f'выполняется {func} с аргументами {args} {kwargs}')
+            start = time.time()
+            try:
+                return await func(*args, **kwargs)
+            finally:
+                end = time.time()
+                total = end - start
+                print(f'{func} завершилась за {total:.4f} с')
+        return wrapped
+    return wrapper
+