Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import time
- async def do_some_prints_with_sleeps(coro_id):
- print(f"[{coro_id}] Hello, i am coro with asyncio.sleeps")
- print(f"[{coro_id}] Will sleep right now for 1 second")
- await asyncio.sleep(1)
- print(f"[{coro_id}] I woke up, but feel sleepy, will sleep 1 second more")
- await asyncio.sleep(1)
- print(f"[{coro_id}] Aaah, that was a great day with a lot of actions")
- return f"lol u fag, and i am coro {coro_id}"
- async def some_client_code_coro():
- print("Creating tasks")
- task_1 = asyncio.create_task(do_some_prints_with_sleeps(1))
- task_2 = asyncio.create_task(do_some_prints_with_sleeps(2))
- print("Tasks are created")
- print(f"Here this guys: \n\ttask_1: {task_1}, \n\ttask_2: {task_2}")
- print("As you can see, there is no output from them")
- print("That's because they are only _scheduled_, and they are waiting for some attention from loop")
- print("We can even freeze this coro for 2 seconds by sync sleep without passing control to the loop, lets do that")
- print("...")
- time.sleep(2)
- print("...")
- print("See? After 2 secs there is no any print calls from our scheduled tasks")
- print("But if we pass the control to the loop by calling async sleep")
- print("...")
- await asyncio.sleep(1.5)
- print("...")
- print('As you can see, 1.5 seconds is not enough to complete our scheduled tasks')
- print(f"Let's take a peek again: \n\ttask_1: {task_1}, \n\ttask_2: {task_2}")
- print("You can see that they are still running and waiting for something (it's internal)")
- print("Let's do that trick with sync sleep again")
- print('...')
- time.sleep(2)
- print('...')
- print('You see? Still no result. Last print calls in our tasks are waiting for their time')
- print("We will pass the control to the async loop one more time, again, by asyncio.sleep()")
- print("...")
- await asyncio.sleep(0.5)
- print("...")
- print("So here they are, last words of our tasks")
- print(f"Let's look at them last time: \n\ttask_1: {task_1}, \n\ttask_2: {task_2}")
- print("Now, they are finished, also you can mention the result field in reprs of this tasks")
- print("The last thing is - how to get their results?")
- print("There are two ways, first is awaiting them")
- result_1 = await task_1
- print(f"await task_1 > {result_1!r}")
- print("But as we now, these Tasks are finished, so we can call the .result() method directly")
- result_2 = task_2.result()
- print(f"task_2.result() > {result_2!r}")
- print("So, that's all, thank you for your attention!")
- print(f"\n!! Be aware !!")
- print("If you will call .result method on running task, the exception like that will be raised:")
- print("'asyncio.base_futures.InvalidStateError: Result is not set.'")
- if __name__ == "__main__":
- asyncio.get_event_loop().run_until_complete(some_client_code_coro())
Advertisement
Add Comment
Please, Sign In to add comment