Search code examples
pythonpython-asynciopython-3.5

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.


Solution

  • You could use asyncio.wait_for:

    future = loop.run_in_executor(None, long_running_function)
    result = await asyncio.wait_for(future, timeout, loop=loop)