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

时间:2017-10-23 18:23:52

标签: python timer

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

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分钟它就应该停止执行。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您可以运行守护进程并检查时间

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()