python 执行多个任务, 哪个任务先返回用这个任务的结果,其他任务停止

 

 

 

 

# coding=utf-8
"""
    @project: icnet
    @Author:angdh
    @file: demo.py
    @date:2023-07-22 10:58
"""

import concurrent.futures

import requests


def task(url):
    # 执行任务的代码
    result = requests.get(url, timeout=10, verify=False)
    return result


executor = concurrent.futures.ThreadPoolExecutor()

future1 = executor.submit(task, "https://www.baidu.com")
future2 = executor.submit(task, "https://www.163.com")
future3 = executor.submit(task, "https://www.qq.com")
future4 = executor.submit(task, "https://www.126.com")
future5 = executor.submit(task, "https://www.sina.com.cn/")

done, not_done = concurrent.futures.wait([future1, future2, future3, future4, future5],
                                         return_when=concurrent.futures.FIRST_COMPLETED)

result = done.pop().result()


print(result.text)

这样,当有任务先执行完时,就会返回该任务的结果,并停止其他任务的执行。注意,这个代码示例中的任务是通过线程池执行的,如果你想使用进程池,可以使用concurrent.futures.ProcessPoolExecutor()代替ThreadPoolExecutor()

 

posted @ 2023-07-22 11:06  AngDH  阅读(13)  评论(0编辑  收藏  举报