我将从循环函数内部调用未指定数目的计数器函数,计数器函数也调用send_request函数
我只想要计数器不要等待send_request应答,当HTTP到达打印时
import requests
import asyncio
import random
async def counter(i):
print("Started counter ",i)
await asyncio.create_task(send_request(random.randint(1,10)))
async def send_request(i):
print("Sending HTTP request ",i)
await asyncio.sleep(i)
r = requests.get('http://example.com')
print(f"Got HTTP response with status {r.status_code} in time {i}")
@app.incomeing_msg(i)
async def loop(i):
asyncio.create_task(counter(i))
asyncio.run(loop())发布于 2022-03-09 15:04:50
顺便说一句,如果您想并行地发送n requests,可以使用threading并编写如下内容:
from threading import Thread
import requests
import random
import time
def counter(i):
print("Started counter ", i)
send_request(random.randint(1, 10))
def send_request(i):
print("Sending HTTP request ", i)
time.sleep(i)
r = requests.get('http://example.com')
print(f"Got HTTP response with status {r.status_code} in time {i}")
def loop():
n = 5
tasks = [Thread(target=counter, args=(i, )) for i in range(n)]
[t.start() for t in tasks]https://stackoverflow.com/questions/71411226
复制相似问题