Nature of Async
July 10, 2024Less than 1 minute
The nature of Async
The nature of Async is an Event Loop.
The result is a coroutine object after invoke a async
function. The function can only be executed after becoming a task.
Basic 1
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
return f"{what} - {delay}"
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, "hello")
await say_after(2, "world")
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
Basic 2
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
return f"{what} - {delay}"
async def main():
print(f"started at {time.strftime('%X')}")
task1 = asyncio.create_task(say_after(1, "hello"))
task2 = asyncio.create_task(say_after(2, "world"))
await task1
await task2
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
Basic 3
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
return f"{what} - {delay}"
async def main():
print(f"started at {time.strftime('%X')}")
ret = await asyncio.gather(
say_after(1, "hello"),
say_after(2, "world")
)
print(f"finished at {time.strftime('%X')}")
Another way to run
loop = asyncio.get_event_loop()
res = loop.run_until_complete(xxx())
loop.close()