在 Python 后端程序中需要使用定时任务时,我们考虑在一个新线程中使用 apscheduler 设置定时任务。
出现了
RuntimeError: There is no current event loop in thread 'Dummy-1'.
的错误。
而在主线程中使用 apscheduler 则不会。
这是因为,apscheduler 中使用了 asyncio.get_event_loop() ,而此时不存在 event loop。默认情况下,在主线程中时,若没有event loop,则 asyncio 会自动创建一个新的 event loop(参见 asyncio.get_event_loop 的文档),而在一个其他线程中,则不会自动创建。
因此在新线程中使用 apscheduler 前,需要手动设置一个 event loop,即:
import asyncio
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
可解决问题。