python - 在python中如何跟踪一段代码是否在一个时间间隔内执行,如果没有则停止

标签 python timer

我有这段代码,我正在使用 pymysql 库执行 sql 语句:

try:
    conn = pymysql.connect(db_endpoint, user=db_username,
                           passwd=db_password, db=db_name, connect_timeout=5)

    cur = conn.cursor()

    result = cur.execute(sql)
    resultSet1 = cur.fetchall()


except:
    print('ERROR: Unexpected error: Could not connect to MySql instance.')
    logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
    sys.exit()

现在我想做的是跟踪执行此查询需要多长时间,如果超过 2 分钟,则停止执行并退出并打印超时消息。我知道我可以使用 default_timer() 在 python 中启动计时器,但我无法进行连续检查以查看它是否应该在达到 2 分钟后立即停止执行。我该怎么做?

最佳答案

你可以运行一个守护进程并检查时间

import time
import multiprocessing as mp

class TimeoutChecker(object):
  def __init__(self, func):
    self.waiting_time = 120
    self._worker_func = func 
    self._queue = mp.Queue()
    self._process = mp.Process()

  def cancel(self):
    if self._process.is_alive():
      self._process.terminate()

  def __call__(self):
    self.cancel()
    self._queue = mp.Queue(1)
    self._process = mp.Process(target=self._worker_func)
    self._process.daemon = True
    self._process.start()
    self.start = time.time()

  def _is_ready(self):
    while self._queue.empty():
      if self.waiting_time < (time.time() - self.start):
        self.cancel()
        return False
    return True

  def value(self):
    if self._is_ready():
      val = self._queue.get()
      return val
    return 'time out'

checker = TimeoutChecker(your function)
checker.value()

关于python - 在python中如何跟踪一段代码是否在一个时间间隔内执行,如果没有则停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46896048/

相关文章:

timer - sw4stm32中如何使能中断功能

c++ - Windows 计时器有时会以两倍的速度运行

c# - 事件处理器乱序处理事件

C++:定时回调后的WHILE循环会阻止回调吗?

python - 我们如何在 python 中打印变量名称及其值,这在调试期间很有用?

python - 与 einsums 的交叉产品

python Pandas : banal apply statements incredibly slow

JavaScript 计时器未更新

python - tensorflow 中的 tf.Session() 之外的参数值是否可用?

python - 获取 XPATH 和 CSS 选择器以使用 Selenium 进行抓取的最佳方法