What is the Task object in asyncio asynchronous programming
Xiaobian to share with you what is the Task object in asyncio asynchronous programming, I believe most people still do not know how, so share this article for everyone's reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
1. Role of Task Objects
Multiple tasks can be added to the event loop to achieve multitask concurrency
2. How to create a task object asyncio.create_task
Note: create_task is only available in python 3.7 and later, just like asyncio.run(),
Before 3.7, task objects could be created using asyncio.ensure_future()
3. Example 1 (currently not recommended) async def func(): print(1) await asyncio.sleep(2) print(2) return "test"async def main(): print("main start") # Python 3.7 and above # task1 = asyncio.create_task(func()) # task2 = asyncio.create_task(func()) #Python 3.7 written before task1 = asyncio.ensure_future(func()) task2 = asyncio.ensure_future(func()) print("main end") ret1 = await task1 ret2 = await task2 print(ret1, ret2)# python3.7 and later #asyncio.run (main())# python3.7 and earlier loop = asyncio.get_event_loop()loop.run_until_complete(main())"""When creating a task, you add the created task to the time loop, so you must have a time loop to create a task, otherwise you will report an error""4. Example 2async def func1(): print(1111) await asyncio.sleep(2) print(2222) return "test"async def main1(): print("main start") tasks = [ asyncio.ensure_future(func1()), asyncio.ensure_future(func1()) ] print("main end") #After successful execution, the second parameter timeout can be added to done. If it is not completed within the timeout period, then pending is the unfinished thing. done, pending = await asyncio.wait(tasks, timeout=1) print(done) #print(pending)# python3.7 previous writing loop = asyncio.get_event_loop()loop.run_until_complete(main1())5. Example 3 (is a simplified version of Example 2 above)"" A simplified version of Method 2, that is, instead of adding task directly to tasks, first add the coroutine object to the list, and add ""async def func2() in the final run: print(1111) await asyncio.sleep(2) print(2222) return "test"tasks = [ func2(), func2()]# python3.7 loop = asyncio.get_event_loop()done, pending = loop.run_until_complete(asyncio.wait(tasks))print(done)print(pending) The above is "What is the Task object in asyncio asynchronous programming" All the contents of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!