“task was destroyed”警告源于创建的asyncio.task未被持有或await,在垃圾回收时被强制销毁。常见于函数内create_task后直接返回、全局列表未管理、或asyncio.run结束前有未完成任务。

为什么 asyncio.create_task() 会触发 “Task was destroyed” 警告?
这个警告不是错误,但说明你创建了一个 asyncio.Task,却在它完成前就丢失了对它的引用,且没有 await 或 cancel —— Python 的垃圾回收器在清理时发现任务仍在运行,于是强制销毁并发出警告。
常见场景包括:在函数里调用 asyncio.create_task() 后直接返回,没把 task 对象存起来或 await;或者把 task 丢进全局列表但忘了后续管理;又或者在 asyncio.run() 结束前有未完成的后台 task。
根本原因不是“用了 create_task”,而是“放任 task 自生自灭”。
如何安全地启动一个“火种任务”(fire-and-forget)?
真正需要后台运行、不阻塞主流程的任务,必须确保它不会被意外回收。有几种可靠做法:
- 把 task 存到一个长期存活的容器里,比如模块级变量
TASKS,并在程序退出前调用asyncio.gather(*TASKS, return_exceptions=True)等待或取消 - 使用
asyncio.create_task()后立即用task.add_done_callback()做清理,避免引用丢失 - 更推荐:改用
asyncio.get_event_loop().create_background_task()(Python 3.12+),它会自动注册到 loop 的后台任务集合中,避免被 gc 错杀
# 推荐写法(兼容 3.7+)
import asyncio
<p>BACKGROUND_TASKS = set()</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8910" title="361SCAN security check your skill python scripts"><img
src="https://img.php.cn/upload/skill/000/000/081/179231049778675.jpg" alt="361SCAN security check your skill python scripts" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill8910" title="361SCAN security check your skill python scripts" class="overflowclass">361SCAN security check your skill python scripts</a>
<p class="overflowclass">扫描并分析已安装技能,用于查看指定技能目录的名称、描述和详情,或列出所有已安装的技能。</p>
</div>
<a rel="nofollow" href="/xiazai/skill8910" title="361SCAN security check your skill python scripts" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>async def background_job():
await asyncio.sleep(5)
print("done")</p><h1>启动并保活</h1><p>task = asyncio.create_task(background_job())
BACKGROUND_TASKS.add(task)
task.add_done_callback(BACKGROUND_TASKS.discard) # 完成后自动移除</p>
哪些写法会悄悄触发警告?
这些看似无害的代码,其实都在制造“孤儿 task”:
-
asyncio.create_task(some_coro())写在函数末尾,没赋值给变量 → task 对象一出作用域就被 gc - 在
<strong>aexit</strong>或信号处理器里调用create_task(),但没做任何持有 → 事件循环可能已关闭 - 使用
asyncio.ensure_future()替代create_task(),而传入的是协程对象(不是 Future)→ 行为一致,但语义更模糊,容易误判生命周期 - 在 Jupyter 或 pytest 中测试异步代码,
asyncio.run()返回后还有 task 在跑 → 循环已关闭,task 必被销毁
特别注意:asyncio.run() 本身会在返回前尝试 cancel 所有未完成 task,但如果 task 正在执行阻塞 IO 或没响应 cancel,就只能等 gc 销毁,警告随之而来。
调试和定位问题 task 的实用技巧
当警告出现但不知道是哪个 task 时,可以用以下方式快速捕获线索:
- 启动时加环境变量:
PYTHONASYNCIODEBUG=1,会让警告带上 task 创建时的栈帧(需asyncio.get_event_loop().set_debug(True)配合) - 在 task 创建处打日志:
print(f"spawned: {task.get_coro().<strong>name</strong>}") - 用
asyncio.all_tasks()在关键点检查当前活跃 task 数量和状态,比如在asyncio.run()返回前打印 - 如果用 pytest,加上
--asyncio-mode=auto并确保每个 test 函数都显式 await 所有启动的 task,或使用pytest-asyncio的 fixture 管理生命周期
最常被忽略的一点:警告里的 “Task was destroyed” 不一定来自你写的代码 —— 第三方库(比如 httpx、aiohttp 的连接池清理逻辑)也可能触发。所以先确认 warning traceback 是否指向你的模块,再动手改。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










