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() # 里面更多的逻辑,真正的关闭

 

相关文章:

  • 2022-01-26
  • 2021-07-24
  • 2022-01-07
  • 2022-12-23
  • 2021-07-15
  • 2021-06-15
  • 2022-01-11
  • 2022-12-23
猜你喜欢
  • 2021-11-16
  • 2021-12-23
  • 2021-06-18
  • 2021-11-02
  • 2021-08-07
  • 2022-12-23
相关资源
相似解决方案