python - 如何限制函数可以运行的时间(添加超时)?

标签 python linux timer timeout scheduling

如何限制一个函数可以运行的最长时间? 例如,使用time.sleep作为占位函数,如何限制time.sleep的运行时间最多为5分钟(300秒)?

import time

try:
    # As noted above `time.sleep` is a placeholder for a function 
    # which takes 10 minutes to complete.
    time.sleep(600)
except:
    print('took too long')

即上面的time.sleep(600)怎么限制300秒后中断呢?

最佳答案

在 POSIX 上,您可以在 signal 中找到一个简单干净的解决方案。模块。

import signal
import time

class Timeout(Exception):
    pass

def handler(sig, frame):
    raise Timeout

signal.signal(signal.SIGALRM, handler)  # register interest in SIGALRM events

signal.alarm(2)  # timeout in 2 seconds
try:
    time.sleep(60)
except Timeout:
    print('took too long')

注意事项:

  • 并非适用于所有平台,例如 window 。
  • 在线程应用程序中不起作用,仅在主线程中起作用。

对于上面的警告会破坏交易的其他读者,您将需要更重量级的方法。最好的选择通常是在单独的进程(或可能是线程)中运行代码,如果花费的时间太长则终止该进程。参见 multiprocessing模块为例。

关于python - 如何限制函数可以运行的时间(添加超时)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43336019/

相关文章:

Python:字典和按字母顺序排序

python - 计算利率 Python Dataframe

linux - 无法连接到服务器上的 Sybase ASE 16.0

linux - 如何修复此 libgcrypt 交叉编译错误?

java - 如何使用java每隔一分钟调用一次方法?

python - 在 Python 中将值转换为各自数据类型的最快方法

python - 如何从 n x n 矩阵生成等高线图?

javascript - 使用frameRate和帧计数器的定时器可靠吗?

python - Selenium、python 和 linux 中的 Chrome webdriver 问题

c - Linux 中间隔计时器的准确性是多少?