In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of the method of Task encapsulation protocol in python, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this article on the method of Task encapsulation in python. Let's take a look.
Description
1. Task is a subclass of Future, and Task is the encapsulation of the protocol. We put multiple Task in the circular scheduling list and wait for the scheduling to be executed.
2. The Task object can track tasks and status. Future (Task is a subclass of Futrue) provides us with processing of the final result in asynchronous programming (the Task class also has state handling capabilities).
3. Encapsulate the cooperative program into Task and join a queue to wait for the call. Do not execute when you just create a Task, but execute when you encounter an await.
Example import asyncio async def func (): print (1) await asyncio.sleep (2) print (2) return "return value" async def main (): print ("main start") # create a coprogram, encapsulate it in a Task object and add it to the task list of the event loop, waiting for the event loop to execute (the default is ready). # when calling task_list = [asyncio.create_task (func (), name= "N1"), asyncio.create_task (func (), name= "N2")] print ("main ends") # when performing an IO operation, it will automatically switch to perform other tasks. # await here waits for all cooperative programs to be executed, and saves the return values of all cooperative programs to done#. If timeout is set, it means that the maximum number of seconds to wait here, and the completed return value of collaborative programs is written to done, and if it is not completed, it is written to pending. Done, pending = await asyncio.wait (task_list, timeout=None) print (done, pending) asyncio.run (main ())
Knowledge point expansion:
The concept and usage of Task
Task is one of the main ways to interact with event loops in python.
To create a Task, it means to encapsulate the collaborative process into a Task instance and track the running / completion status of the collaborative program, which can be used to obtain the results of the collaborative program in the future.
The core role of Task: add multiple concurrent tasks to the event loop
Specifically, the Task is created through asyncio.create_task (), and the collaborator object is added to the event loop, waiting to be scheduled for execution.
Note: later versions of Python support asyncio.create_task (). Before that, it was written as loop.create_task (). During the development process, you need to pay attention to the compatibility of code writing with different versions of python.
It should be pointed out that the co-program will not be started immediately after it is encapsulated as Task, but will only be executed when some code await this Task.
When multiple Task are added to a task_list, the Task will not be executed during the process of adding Task, and the Task object must be added to the event loop with await asyncio.wait () or await asyncio.gather () to execute asynchronously.
In general, in development, the common way to write is as follows:
-- create an empty task_list list first
Then create a Task with asyncio.create_task ()
-- then add Task objects to task_list
Finally, the Task object is added to the event loop to execute asynchronously using await asyncio.wait or await asyncio.gather.
Note: when creating Task objects, in addition to using asyncio.create_task (), you can also use the lowest level of loop.create_task () or asyncio.ensure_future (), both of which can be used to create Task objects, which will be covered later in this article on ensure_future.
Example of Task usage code:
Import asyncioimport arrowdef current_time (): "" get the current time: return: "" cur_time = arrow.now () .to ("Asia/Shanghai") .format ("YYYY-MM-DD HH:mm:ss") return cur_timeasync def func (sleep_time): func_name_suffix = sleep_time # use sleep_time (the length of waiting time of the function Imaco) as the function name suffix To distinguish the task object print (f "[{current_time ()}]) execute the asynchronous function {func.__name__}-{func_name_suffix}") await asyncio.sleep (sleep_time) print (f "[{current_time ()}] function {func.__name__}-{func_name_suffix} finished") return f "[[{current_time ()}] To function {func.__name__}-{func_name_suffix} execution result] "async def run (): task_list = [] for i in range (5): task = asyncio.create_task (async_func (I)) task_list.append (task) done Pending = await asyncio.wait (task_list Timeout=None) for done_task in done: print (f "[{current_time ()}] get the execution result {done_task.result ()}") def main (): loop = asyncio.get_event_loop () loop.run_until_complete (run ()) if _ _ name__ = = "_ _ main__": main () on the method of Task Encapsulation Protocol in python Thank you for reading! I believe you all have a certain understanding of "the method of Task encapsulation process in python". If you want to learn more knowledge, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.