0

Suppose, I have a method from a third-party library to which I have no access or I don't want to change its source code. I want to be able to call that method and if it doesn't return a result within some period of time, then I want to either cancel its execution or go forward:

# start a timer or something


# call that method
third_party_method()

# if the time has elapsed, say, 1 minute has passed with no result

# then cancel it (preferably)
#  and print("too late")

# otherwise print("on time")

How can I do that? Is there an easy more or less and standard way?

1 Answers1

0

The following will not kill the work if it takes too long, but will at least let you know:

def f():
    # sleep for 10 seconds
    import time
    time.sleep(10)

def do_we_give_up():
    from concurrent import futures
    executor = futures.ThreadPoolExecutor(max_workers=1)
    future = executor.submit(f)

    # give it a second
    try: 
        for x in futures.as_completed([future], 1):
           # the result
           print(x.result())
    except futures.TimeoutError:
        # no result
        print("timed out")

Then

>>> do_we_give_up()
timed out
donkopotamus
  • 22,114
  • 2
  • 48
  • 60