You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加运行定时任务遇RuntimeWarning及tracemalloc配置问题求助

问题排查与解决方案

1. 解决RuntimeWarning: coroutine 'send_message_date' was never awaited

问题根源

APScheduler的BlockingScheduler是同步调度器,无法直接执行异步协程函数(send_message_date用async定义)。调度器调用该函数时只会生成协程对象,不会触发执行,因此抛出未被await的警告。同时BlockingScheduler.start()会阻塞线程,和aiogram的异步事件循环冲突。

修复方案

  • 替换调度器类型:使用AsyncIOScheduler(APScheduler专为异步环境设计的调度器),适配aiogram的事件循环。
  • 调整调度器启动方式:用start_in_background()替代start(),避免阻塞aiogram的运行。
  • 避免重复启动调度器:添加判断逻辑,仅在调度器未运行时启动。

修改后的代码示例:

# 替换原BlockingScheduler的导入
from apscheduler.schedulers.asyncio import AsyncIOScheduler

# 初始化异步调度器
sched = AsyncIOScheduler()

@dp.message(TimeTaskOrder.date)
async def add_time_task_date(message: types.Message, state: FSMContext):
    chat_id = message.chat.id
    task['date'] = datetime.datetime.strptime(message.text, "%d.%m.%Y %H:%M")
    taskmodel = TimeTask(profile=task['profile'], title=task['title'], date=task['date'])
    await taskmodel.asave()
    await message.answer('task is created')

    # 添加异步任务到调度器
    sched.add_job(send_message_date, 'date', run_date=task['date'], args=[bot, chat_id, task['title']])
    # 仅在调度器未运行时启动
    if not sched.running:
        sched.start_in_background()

2. 处理Enable tracemalloc to get the object allocation traceback

这个提示是Python建议开启tracemalloc模块追踪内存分配的详细回溯,用于定位内存问题。若需要排查内存相关问题,在代码最开头添加:

import tracemalloc
tracemalloc.start()

若无需追踪内存,可直接忽略该提示,不影响程序核心功能。

内容的提问来源于stack exchange,提问作者narcel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 04:00:26