nim4n
nim4n

Reputation: 1829

how to raise a timeout exception after X seconds in python

I have a function and I need to raise exception after X seconds how can I do this? I try this code but It doesen't work:

from eventlet.timeout import Timeout
timeout = Timeout(seconds, exception)
try:
   do somethins
finally:
   timeout.cancel()

Upvotes: 0

Views: 6573

Answers (1)

falsetru
falsetru

Reputation: 369074

According to the timeout documentation:

There are two Timeout caveats to be aware of:

  • If the code block in the try/finally or with-block never cooperatively yields, the timeout cannot be raised. In Eventlet, this should rarely be a problem, but be aware that you cannot time out CPU-only operations with this class.
  • If the code block catches and doesn't re-raise BaseException (for example, with except:), then it will catch the Timeout exception, and might not abort as intended.

If you are doing expensive calculation without doing any IO/sleep in a loop, timeout will not occur.

Upvotes: 1

Related Questions