Asyncio create_task在while循环中异常:无法按预期间隔执行
asyncio任务执行频率异常问题分析与修复
你的代码出现预期外的日志输出频率,核心原因是**test_function的循环内重复创建other_function的异步任务**:
每次test_function的循环执行到asyncio.create_task(other_function(...))时,都会新建一个独立的异步任务。第一个任务会在20秒后唤醒执行后续逻辑,但之后每4秒就会有新的other_function任务被创建并运行,多个任务并发执行,最终导致每隔4秒就会出现other_function的日志。
修复方案
将other_function任务的创建逻辑移到test_function的循环外部,确保只创建一次任务:
import asyncio import time async def test_function(value: list, remove_val: str): t_end = time.time() + 60 # 仅初始化一次other_function异步任务 task = asyncio.create_task(other_function(value, remove_val)) print("process started") while time.time() < t_end: await asyncio.sleep(4) print(f"{t_end - time.time()} seconds left") print("Four seconds passed") # 等待异步任务执行完成 await task async def other_function(value: list, remove_val: str): t_end = time.time() + 60 arrayList = value while time.time() < t_end: if remove_val in arrayList: arrayList.remove(remove_val) print(f"Value {remove_val} removed! array now is {arrayList}!") await asyncio.sleep(20) print(f"{t_end - time.time()} seconds for other_function left") arrayList.append(remove_val) print(f"Value {remove_val} added! array now is {arrayList}!") arr= ["joe", "cody", "sam"] asyncio.run(test_function(arr, "sam"))
修复后逻辑说明
other_function仅被创建为一个异步任务,它会按照自身代码逻辑,每20秒执行一次移除、添加元素的操作test_function保持每4秒输出一次日志的频率,两个任务独立并发运行,互不干扰,符合预期执行节奏
内容的提问来源于stack exchange,提问作者fsssaiyan
相关产品推荐
相关产品推荐

