gpt4 book ai didi

python - 运行时错误 : There is no current event loop in thread in async + apscheduler

转载 作者:IT老高 更新时间:2023-10-28 20:30:15 25 4
gpt4 key购买 nike

我有一个异步功能,需要每 N 分钟运行一次 apscheduller。下面有一段python代码

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

但是当我尝试运行它时,我有下一个错误信息

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,

最佳答案

在您的 def demo_async(urls) 中,尝试替换:

loop = asyncio.get_event_loop()

与:

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

关于python - 运行时错误 : There is no current event loop in thread in async + apscheduler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46727787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com