import asyncio
import time
from contextlib import contextmanager, asynccontextmanager
async def fun(n):
print(f"{fun.__name__}{n}")
await asyncio.sleep(2)
print(f"{fun.__name__}{n} end")
return f"{fun.__name__}{n}"
async def foo(n):
print(f"{foo.__name__}{n}")
await asyncio.sleep(2)
print(f"{foo.__name__}{n} end")
return f"{foo.__name__}{n}"
def record_time(func):
async def wrapper(*args, **kwargs):
t1 = time.time()
await func(*args, **kwargs)
print(f"decorator run time {time.time() - t1}")
return wrapper
def print_number(n,cnt):
start = n
end = start + cnt
for i in range(start, end):
print(f"{print_number.__name__}:{i}")
time.sleep(1)
async def set_future(fu):
await asyncio.sleep(2)
print("set future")
fu.set_result("set future")
class Incrementer:
def __init__(self,start,cnt):
self.i = start
self.max = start + cnt
def __aiter__(self):
return self
async def __anext__(self):
if self.i < self.max:
self.i += 1
return f"{Incrementer.__name__}:{self.i}"
else:
raise StopAsyncIteration
async def async_for():
async for i in Incrementer(1,5):
print(i)
await asyncio.sleep(1)
class AsyncContextManagerClass:
def __init__(self,wait_time):
self.conn = "conn"
self.wait_time_sec = wait_time
async def wait_time(self):
print(f"{AsyncContextManagerClass.__name__}: {self.wait_time_sec} sec")
await asyncio.sleep(self.wait_time_sec)
async def __aenter__(self):
print(f"{AsyncContextManagerClass.__name__}:enter")
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
print(f"{AsyncContextManagerClass.__name__}:exit")
self.conn = None
class AsyncContextManagerFunction:
def __init__(self,wait_time):
self.wait_time = wait_time
pass
@asynccontextmanager
async def async_context_manager(self):
wait_time = self.wait_time
print(f"{AsyncContextManagerFunction.__name__}:enter")
time1 = asyncio.get_running_loop().time()
await asyncio.sleep(wait_time)
yield "conn"
print(f"{AsyncContextManagerFunction.__name__}: {asyncio.get_running_loop().time() - time1}")
print(f"{AsyncContextManagerFunction.__name__}:exit")
@record_time
async def main():
print("main")
loop = asyncio.get_running_loop()
t1 = loop.time()
task_list = [asyncio.create_task(fun(i)) for i in range(3)]
task_list2 = [asyncio.create_task(foo(i)) for i in range(3)]
fu = loop.create_future()
thread_future = loop.run_in_executor(None, print_number, 1, 5)
wtt = AsyncContextManagerFunction(1)
async with AsyncContextManagerClass(wait_time=2) as wt:
async with wtt.async_context_manager() as wt2:
print(wt2)
total_task_list = task_list + task_list2 + \
[thread_future,
async_for(),
wt.wait_time()
] + [
set_future(fu),
]
done, pending = await asyncio.wait(total_task_list, timeout=1000, return_when=asyncio.ALL_COMPLETED)
print("done", done)
print("pending", pending)
print("main end")
print(f"run time {(loop.time() - t1)}")
asyncio.run(main())