是否可以同时安排异步和同步功能



参考代码

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from telegram.ext import ApplicationBuilder
def function_one(args):
#DO SOMETHING
async def function_two(args):
await #DO SOMETHING ELSE
scheduler_one = BackgroundScheduler()
scheduler_two = AsyncIOScheduler()
scheduler_one.add_job(function_one, 'interval', minutes = 5, args = ( ,))
scheduler_two.add_job(function_two, 'interval', minutes = 1, args = ( ,))
if __name__ == "__main__":
application = ApplicationBuilder().token(API_KEY).build()
scheduler_one.start()
scheduler_two.start()
application.run_polling()

模块版本

  • Python v3.10.6
  • python电报bot v2.0a1
  • apscheduler v3.9.1

输出:只有scheduler_two开始工作,而scheduler_one将被忽略。因此,只有一个调度程序被激活。

问题描述:我需要function_onefunction_two定期工作。function_two依赖于需要等待的python电报botBot类。

尝试次数

  • 我已经尝试将scheduler_one用于两者,但我收到了关于function_two的错误消息
/app/.heroku/python/lib/python3.10/concurrent/futures/thread.py:85: RuntimeWarning: coroutine 'function_two' was never awaited
2022-09-15T14:46:30.247039+00:00 app[worker.1]:   del work_item
2022-09-15T14:46:30.247040+00:00 app[worker.1]: RuntimeWarning: Enable tracemalloc to get the object allocation traceback
  • 然后,我尝试将scheduler_two用于两者,但只有function_two有效。

  • 最后,我尝试在function_two内部调用function_one,但也不起作用。

因此,我的问题是,是否有任何方法可以同时运行这两个函数或解决方法?

我想指出,python-telegram-bot附带了内置的JobQueue,它实际上是基于APScheduler的。因此,自己设置时间表可能根本没有必要。请注意,在v13.x中,PTB使用BackgroundScheduler,而在v20.x中(当前处于预发布模式(,PTB则使用AsyncIOScheduler,因为v20已转换为asyncio

关于协同程序函数与正常函数作为作业回调,我不得不评论:

  • function_one定义为协程函数也不会影响函数中的任何代码,这样您就可以直接在AsyncIOScheduler(或JobQueue(中使用它
  • BackgroundScheduler是基于线程的。我通常会避免将线程与asyncio混合使用。因此,如果function_one执行任何I/O密集型任务,我建议将这些任务返工为基于asyncio的方案

最新更新