Timeout when using run_in_executor and asyncio

I use asyncio to run part of the lock code as follows:

result = await loop.run_in_executor(None, long_running_function)

My question is: can I set a timeout to execute long_running_function?

Basically, I don’t want it to long_running_functionlast more than 2 seconds, and I can’t do the correct processing of the timeout inside it, because this function comes from a third-party library.

+4
source share
2 answers

You can use asyncio.wait_for :

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

Warning about canceling continuous functions:

Future, loop.run_in_executor asyncio.wait_for, long_running_function x , long_running_function, concurrent.futures, , , concurrent.futures.Future.

+6

Source: https://habr.com/ru/post/1621616/


All Articles