Asyncio 处理长时间运行的任务

Rah*_*hul 3 python python-asyncio

我昨天刚刚学习了 python 3.5 的异步。

这就是我今天想要完成的任务。

import asyncio  
import time
import requests

async def foo():
    """Some Long Running Taks"""
    requests.get("http://stackoverflow.com/questions/41301031/asyncio-on-long-running-task")
    print("foo")

async def bar():
    """Some Quick Task"""
    print("bar")

while True:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(foo(), bar()))
    loop.close()
    time.sleep(2)

#Expected output
"""
>>>bar
>>>bar
>>>bar
>>>bar
>>>bar
>>>foo
and so on
"""
Run Code Online (Sandbox Code Playgroud)

使用 python async/await 可以吗?

Udi*_*Udi 6

您的代码中存在一些问题:

  1. requests 不支持 asyncio,请使用aiohttp代替。

  2. 您的协程仅在循环运行时运行:loop.run_until_complete()在代码中仅调用一次,并使用await(或asycio.ensure_future()或loop.create_task()) 安排许多(短或长)任务。

这是一个示例,执行与您尝试执行的操作类似的操作:

# make sure to run `pip install aiohttp` first!!!

import asyncio

import aiohttp


async def slow_fetch(delay):
    url = "http://httpbin.org/delay/{}".format(delay)
    print("Getting ", url)
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            text = await resp.text()
    print("Got {}, {} chars".format(url, len(text)))


async def quick_loop():
    print("enter quick_loop")
    for i in range(10):
        await asyncio.sleep(1)
        print("quick_loop", i)
    print("exit quick_loop")


loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
    slow_fetch(3),
    slow_fetch(4),
    quick_loop(),
))
loop.close()
Run Code Online (Sandbox Code Playgroud)