求助:无需预定义任务列表发送异步请求,解决服务器负载与延迟问题
异步持续请求的间隔控制与动态任务解决方案
针对你遇到的线程脚本负载过高、asyncio预定义任务列表受限、gather调用延迟等问题,这里提供直接的异步实现方案,解决核心需求:
核心思路
- 动态创建任务替代预定义列表:通过循环持续生成异步任务,无需提前确定总请求数
- 避免单一Session缓存:每次请求新建
aiohttp.ClientSession,配合请求头禁用缓存 - 抛弃批量gather:单个任务独立处理或并发控制下动态管理,消除批量等待延迟
基础版:串行间隔请求
适合需要严格按间隔发起请求,且每次等待前一个请求完成的场景:
import asyncio import aiohttp async def send_single_request(target_url): # 每次请求新建Session,彻底避免缓存共享 async with aiohttp.ClientSession() as session: # 额外添加请求头禁用缓存,双重保险 headers = {"Cache-Control": "no-cache", "Pragma": "no-cache"} async with session.get(target_url, headers=headers) as resp: # 可根据需求替换为resp.json()或其他处理逻辑 return await resp.text() async def run_continuous_requests(url, interval): while True: # 发起请求并等待结果(若无需等待结果,可直接用asyncio.create_task异步执行) response = await send_single_request(url) print(f"请求完成,响应摘要:{response[:60]}...") # 等待指定间隔后发起下一次请求 await asyncio.sleep(interval) if __name__ == "__main__": target_url = "https://your-target-api.com" request_interval = 2 # 间隔2秒 asyncio.run(run_continuous_requests(target_url, request_interval))
进阶版:并发控制+固定间隔发起
如果需要同时处理多个请求,但严格按间隔发起新请求,且控制最大并发数:
import asyncio import aiohttp async def send_request_with_semaphore(url, semaphore): # 信号量控制最大并发数 async with semaphore: async with aiohttp.ClientSession() as session: headers = {"Cache-Control": "no-cache", "Pragma": "no-cache"} async with session.get(url, headers=headers) as resp: return await resp.text() async def run_controlled_concurrent_requests(url, interval, max_concurrent): semaphore = asyncio.Semaphore(max_concurrent) active_tasks = [] try: while True: # 动态创建新任务并加入列表 new_task = asyncio.create_task(send_request_with_semaphore(url, semaphore)) active_tasks.append(new_task) # 清理已完成的任务,避免内存泄漏 active_tasks = [task for task in active_tasks if not task.done()] # 等待指定间隔后发起下一个请求 await asyncio.sleep(interval) except asyncio.CancelledError: # 程序终止时取消所有未完成任务 for task in active_tasks: task.cancel() await asyncio.gather(*active_tasks, return_exceptions=True) if __name__ == "__main__": target_url = "https://your-target-api.com" request_interval = 1 # 每秒发起一个请求 max_concurrent = 3 # 最多同时处理3个请求 try: asyncio.run(run_controlled_concurrent_requests(target_url, request_interval, max_concurrent)) except KeyboardInterrupt: print("用户终止程序")
精确间隔优化
如果需要忽略请求耗时,严格按固定时间间隔发起请求(比如每2秒发起一次,不管上一次请求耗时多久):
async def run_precise_interval_requests(url, interval): loop = asyncio.get_event_loop() last_start_time = loop.time() while True: # 记录当前发起时间 last_start_time += interval # 发起请求 response = await send_single_request(url) print(f"请求完成,响应摘要:{response[:60]}...") # 计算需要等待的时间,保证下一次发起时间严格对齐间隔 sleep_duration = last_start_time - loop.time() if sleep_duration > 0: await asyncio.sleep(sleep_duration)
关键说明
- Session隔离:每次请求新建
ClientSession,彻底避免Session级别的缓存(比如Cookie、连接池缓存),配合请求头进一步禁用服务器端缓存 - 无预定义任务:通过
while True循环动态生成任务,支持无限持续请求 - 无gather延迟:不再批量等待所有任务完成,而是单个任务独立处理或动态管理活跃任务,消除批量等待带来的延迟
内容的提问来源于stack exchange,提问作者Deathly boy
相关产品推荐
相关产品推荐

