参考代码:
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_one
和function_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
的方案