Any concurrent.futures timeout that actually works?

前端 未结 2 1069
死守一世寂寞
死守一世寂寞 2020-12-11 18:39

Tried to write a process-based timeout (sync) on the cheap, like this:

from concurrent.futures import ProcessPoolExecutor

def call_with_timeout(func, *args,         


        
2条回答
  •  情书的邮戳
    2020-12-11 18:45

    You might want to take a look at pebble.

    Its ProcessPool was designed to solve this exact issue: enable timeout and cancellation of running tasks without the need of shutting down the entire pool.

    When a future times out or is cancelled, the worker gets actually terminated effectively stopping the execution of the scheduled function.

    Timeout:

    pool = pebble.ProcessPool(max_workers=1)
    future = pool.schedule(func, args=args, timeout=1)
    try:
        future.result()
    except TimeoutError:
        print("Timeout")
    

    Example:

    def call_with_timeout(func, *args, timeout=3):
        pool = pebble.ProcessPool(max_workers=1)
        with pool:
            future = pool.schedule(func, args=args, timeout=timeout)
            return future.result()
    

提交回复
热议问题