任务超时功能
背景:
有些情况下,我们需要sleep等待运行结果,但是,这个等待时间是有限的,一旦超出等待时间限制,此时,我们判定它失败。
代码(python2.7):
# -*- coding: utf-8 -*- import time from threading import Thread from lib.all_error_type import TestItemError ThreadStop = Thread._Thread__stop def time_limited(timeout): def decorator(function): def decorator2(*args, **kwargs): class TimeLimited(Thread): def __init__(self, _error=None, ): Thread.__init__(self) self.error = _error self.result = None def run(self): try: self.result = function(*args, **kwargs) except Exception as e: self.error = e def stop(self): if self.isAlive(): ThreadStop(self) t = TimeLimited() t.start() t.join(timeout) if t.error: t.stop() raise t.error elif t.isAlive(): t.stop() raise TestItemError(4320) return t.result return decorator2 return decorator if __name__ == "__main__": @time_limited(4) # 设置运行超时时间2S def fn_1(secs): time.sleep(secs) return 'Finished without timeout' try: print(fn_1(3)) # 设置函数执行3S except TestItemError as e: print(str(e))
python3.8
# -*- coding: utf-8 -*- import time from threading import Thread from lib.all_error_type import TestItemError def time_limited(timeout): def decorator(function): def decorator2(*args, **kwargs): class TimeLimited(Thread): def __init__(self, _error=None, ): Thread.__init__(self) self.error = _error self.result = None def run(self): try: self.result = function(*args, **kwargs) except Exception as e: self.error = e t = TimeLimited() t.setDaemon(True) t.start() t.join(timeout) if t.error: raise t.error elif t.is_alive(): raise TestItemError(4320) return t.result return decorator2 return decorator if __name__ == "__main__": @time_limited(4) # 设置运行超时时间2S def fn_1(secs): time.sleep(secs) return 'Finished without timeout' try: print(fn_1(3)) # 设置函数执行3S except TestItemError as e: print(str(e))