如何在后台运行定时异步函数?已遇协程未等待警告
后台运行定时异步函数的解决方案
你的问题出在BackgroundScheduler是同步调度器,无法直接处理异步协程,所以会出现"coroutine was never awaited"的警告。另外你不需要await print('Hello World'),因为print是同步函数,await对它无效。
可以通过同步包装函数调用异步协程的方式解决,具体代码如下:
import asyncio from apscheduler.schedulers.background import BackgroundScheduler # 异步函数 async def checking(): print('Hello World') # 移除不必要的await # 同步包装函数,用于调度器调用 def run_checking(): asyncio.run(checking()) # 初始化后台调度器 scheduler = BackgroundScheduler() # 添加定时任务,执行同步包装函数 scheduler.add_job(run_checking, 'cron', hour='02', minute='11') # 启动调度器 scheduler.start() # 保持主进程运行,否则后台调度器会随主进程退出 try: while True: asyncio.sleep(1) except KeyboardInterrupt: # 捕获中断信号,优雅关闭调度器 scheduler.shutdown()
关键说明:
BackgroundScheduler仅支持执行同步函数,因此需要用run_checking这样的同步函数作为中间层,通过asyncio.run()来启动异步协程。- 主程序末尾的循环是必须的,否则主进程结束后,后台调度器也会停止运行。你也可以用
time.sleep()替代asyncio.sleep(),只要能保持主进程存活即可。
内容的提问来源于stack exchange,提问作者dohyunii
相关产品推荐
相关产品推荐

