2017-10-13 183 views
3

我有一個異步函數,需要每隔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,

回答

2

只需將fetch_all直接傳遞給scheduler.add_job()即可。 asyncio調度程序支持協同功能作爲工作目標。

如果目標可調用函數是而不是協程函數,它將在工作線程中運行(由於歷史原因),因此是例外。

+0

謝謝亞歷克斯的評論! 它可以幫助我:) –

12

def demo_async(urls),嘗試更換:

loop = asyncio.get_event_loop()

有:

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

+1

感謝prezha。你的選擇也有效! :) –

+0

不客氣@ValeraShutylev,我很高興它爲你工作! ;-) – prezha

+0

做**不**做到這一點!這隻會導致第二個事件循環運行。鑑於APScheduler對協同功能的本地支持,它是毫無意義的。如果您嘗試使一個事件循環中的事件與第一個事件循環相互作用,將會發生不好的事情。 –

相關問題