单进程子进程超时处理方法

一、 使用eventlet  ——  单进程有效,多进程失效

1. 安装:

pip3 install eventlet

2. 执行代码:

import time
import eventlet  # 导入eventlet

eventlet.monkey_patch()  # 必须加这条代码
flag = False 
abort_time = 2
print('超时等待时间:{} s'.format(abort_time))
with eventlet.Timeout(abort_time, False):  # 设置超时时间为abort_time秒
    print('开始执行程序') 
    time.sleep(abort_time+2)
    flag = True
if flag == True:
    print('超时终止未生效。')
else:
    print('超时终止生效。')

输出:

二 使用timeout_decorator ——  单进程有效,多进程失效

1. 安装:

pip3 install timeout-decorator

2. 代码:​​​​​​​

import time
import timeout_decorator

@timeout_decorator.timeout(5)
def mytest():
    print("Start")
    for i in range(1,10):
        time.sleep(1)
        print("{} seconds have passed".format(i))

if __name__ == '__main__':
    mytest()
 
  

三  守护进程执行任务监控 —— 多进程有效

1. 原始方案参考:

https://stackoverflow.com/questions/29494001/how-can-i-abort-a-task-in-a-multiprocessing-pool-after-a-timeout

建立一个守护进程池。由守护进程新建一个执行任务的进程,并监控执行进程的返回值,如果返回超时,则杀掉执行进程。

2. 代码:

import multiprocessing
from multiprocessing.dummy import Pool as ThreadPool
from functools import partial

def worker(x, y, z):
    print('执行任务函数') # Do whatever here

def collectMyResult(result):
    print("Got result {}".format(result))

def abortable_worker(func, *args, **kwargs):
    timeout = kwargs.get('timeout', None)
    p = ThreadPool(1)
    res = p.apply_async(func, args=args)
    try:
        out = res.get(timeout)  # Wait timeout seconds for func to complete.
        return out
    except multiprocessing.TimeoutError:
        print("Aborting due to timeout")
        raise

if __name__ == "__main__":
    pool = multiprocessing.Pool(maxtasksperchild=1)
    featureClass = [[1000,k,1] for k in range(1,20,5)] #list of arguments
    for f in featureClass:
      abortable_func = partial(abortable_worker, worker, timeout=3)
      pool.apply_async(abortable_func, args=f,callback=collectMyResult)
    pool.close()
    pool.join()

输出:

单进程子进程超时处理方法_第1张图片

你可能感兴趣的:(Coding,python,开发语言)