RuntimeError:async + apscheduler中的线程中没有当前的事件循环
我有一个异步函数,需要每隔N分钟运行一次apscheduller。 下面有RuntimeError:async + apscheduler中的线程中没有当前的事件循环
URL_LIST = ['<url1>',
'<url2>',
'<url2>',
]
def demo_async(urls):
"""Fetch list of web pages asynchronously."""
loop = asyncio.get_event_loop() # event loop
future = asyncio.ensure_future(fetch_all(urls)) # tasks to do
loop.run_until_complete(future) # loop until done
async def fetch_all(urls):
tasks = [] # dictionary of start times for each url
async with ClientSession() as session:
for url in urls:
task = asyncio.ensure_future(fetch(url, session))
tasks.append(task) # create list of tasks
_ = await asyncio.gather(*tasks) # gather task responses
async def fetch(url, session):
"""Fetch a url, using specified ClientSession."""
async with session.get(url) as response:
resp = await response.read()
print(resp)
if __name__ == '__main__':
scheduler = AsyncIOScheduler()
scheduler.add_job(demo_async, args=[URL_LIST], trigger='interval', seconds=15)
scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
# Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
try:
asyncio.get_event_loop().run_forever()
except (KeyboardInterrupt, SystemExit):
pass
一个Python代码,但是当我试图运行它,我有下一个错误信息
Job "demo_async (trigger: interval[0:00:15], next run at: 2017-10-12 18:21:12 +04)" raised an exception.....
..........\lib\asyncio\events.py", line 584, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread '<concurrent.futures.thread.ThreadPoolExecutor object at 0x0356B150>_0'.
你能帮我吗? Python 3.6,APScheduler 3.3.1,
只需将fetch_all
直接传递给scheduler.add_job()
即可。 asyncio调度程序支持协同功能作为工作目标。
如果目标可调用函数是而不是协程函数,它将在工作线程中运行(由于历史原因),因此是例外。
在def demo_async(urls)
,尝试更换:
loop = asyncio.get_event_loop()
有:
loop = asyncio.new_event_loop() asyncio.set_event_loop(loop)
感谢prezha。你的选择也有效! :) –
不客气@ValeraShutylev,我很高兴它为你工作! ;-) – prezha
做**不**做到这一点!这只会导致第二个事件循环运行。鉴于APScheduler对协同功能的本地支持,它是毫无意义的。如果您尝试使一个事件循环中的事件与第一个事件循环相互作用,将会发生不好的事情。 –
谢谢亚历克斯的评论! 它可以帮助我:) –