码迷,mamicode.com
首页 > 编程语言 > 详细

python asyncio 关闭task

时间:2019-07-20 17:30:38      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:inter   pre   name   eve   keyboard   ppi   can   orm   _for   

import asyncio
import time

async def get_html(sleep_times):
    print("waiting")
    await asyncio.sleep(sleep_times)
    print("done after {}s".format(sleep_times))


if __name__ == "__main__":
    task1 = get_html(2)
    task2 = get_html(3)
    task3 = get_html(3)

    tasks = [task1, task2, task3]

    loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(asyncio.wait(tasks))
    except KeyboardInterrupt as e:
        all_tasks = asyncio.Task.all_tasks()
        for task in all_tasks:
            print("cancel task")
            print(task.cancel())
        loop.stop() # 只是将stopping的标记置位true
        loop.run_forever() # 在stop后一定要运行这段代码,不然会抛异常
    finally:
        loop.close() # 里面更多的逻辑,真正的关闭

 

python asyncio 关闭task

标签:inter   pre   name   eve   keyboard   ppi   can   orm   _for   

原文地址:https://www.cnblogs.com/callyblog/p/11218228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!