Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout handling while using run_in_executor and asyncio

I'm using asyncio to run a piece of blocking code like this:

result = await loop.run_in_executor(None, long_running_function)

My question is: Can I impose a timeout for the execution of long_running_function?

Basically I don't want long_running_function to last more than 2 seconds and I can't do proper timeout handling within it because that function comes from a third-party library.

like image 564
Andrés Fernández Avatar asked Dec 24 '15 12:12

Andrés Fernández


2 Answers

A warning about cancelling long running functions:

Although wrapping the Future returned by loop.run_in_executor with an asyncio.wait_for call will allow the event loop to stop waiting for long_running_function after some x seconds, it won't necessarily stop the underlying long_running_function. This is one of the shortcomings of concurrent.futures and to the best of my knowledge there is no simple way to just cancel a concurrent.futures.Future.

like image 74
Jashandeep Sohi Avatar answered Nov 17 '22 19:11

Jashandeep Sohi


You could use asyncio.wait_for:

future = loop.run_in_executor(None, long_running_function)
result = await asyncio.wait_for(future, timeout, loop=loop)
like image 7
Vincent Avatar answered Nov 17 '22 20:11

Vincent