简单示例
# -*- coding: utf-8 -*- import signal import time def handle(signum, frame): print("超时了") # 注册信号 signal.signal(signal.SIGALRM, handle) # 设置信号发送时间 signal.alarm(3) # 开启闹钟信号 print("开启信号") time.sleep(5) print("关闭信号") signal.alarm(0) # 关闭闹钟信号 """ sleep 2 开启信号 关闭信号 sleep 5 开启信号 超时了 关闭信号 """
处理超时示例
import signal class TimeOutException(Exception): pass def handle(signum, frame): raise TimeOutException("运行超时!") def set_timeout(timeout, callback): def wrapper(func): def inner(*args, **kwargs): try: signal.signal(signal.SIGALRM, handle) signal.alarm(timeout) # 开启闹钟信号 rs = func(*args, **kwargs) signal.alarm(0) # 关闭闹钟信号 return rs except TimeOutException as e: callback() return inner return wrapper def process_time(): print("超时了") @set_timeout(40, process_time) def function(): pass
备注:超时信号只能设置在主线程函数,不能设置在子线程函数
参考