问题描述
我有一个异步功能,需要每隔N分钟用apscheduller来运行一次。
下面有一个python代码
I have a async function and need to run in with apscheduller every N minutes.There is a python code below
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
但是当我尝试运行它时,我会看到下一个错误信息
But when i tried to run it i have the next error info
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,
Could you please help me with this?Python 3.6, APScheduler 3.3.1,
推荐答案
只需通过直接从fetch_all
到 scheduler.add_job()
。asyncio调度程序支持协程函数作为作业目标。
Just pass fetch_all
to scheduler.add_job()
directly. The asyncio scheduler supports coroutine functions as job targets.
如果目标可调用对象不是协程函数,则为r Un(由于历史原因)处于工作线程中,因此是一个例外。
If the target callable is not a coroutine function, it will be run in a worker thread (due to historical reasons), hence the exception.
这篇关于RuntimeError:异步+ Apscheduler中的线程中没有当前事件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!