使用定时线程来终止查询

2024-10-03 13:24:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用时间线程终止正在运行的查询。我尝试过不同的实现,但似乎什么都不管用。你知道吗

现在我调用函数executeTimedQuery,它启动一个10秒的计时器,如果查询运行时间太长,就会执行这个计时器。一开始self.cursor.execute执行(自我查询)获取run,这是我要在10秒后终止的长时间运行的查询。出于某种原因,即使计时器中的函数被启动,游标仍在运行长时间运行的查询,并且不会运行KILL CONNECTION{pId};命令;。它等待长查询完成,然后在结束时终止连接。你知道吗

我做错了什么?最好的解决方法是什么?我现在很想找到解决办法。:/

到目前为止,我有以下代码:

def killDBConnection(self, processId):
  '''
  This takes in a processId, which is the mysql cursor connection process 
  id.
  '''
  killQuery = 'KILL CONNECTION {pId};'.format(pId=processId)
  try:
    self.cursor.execute(killQuery)
  except:
    print('Testing')
  return 'temp'


def executeTimedQuery(self, ret):
  '''
  This takes in a dictionary.
  '''
  pID =  self.getProcessId()
  try:
    Timer(10.0, self.killDBConnection, [pID]).start()
    self.cursor.execute(self.query)
    ret['executable'] = True
    ret['data'] = self.cursor.fetchall()
    ret['headers'] = tuple([col[0] for col in self.cursor.description])
    t.cancel()
  except:
    print('executeTimedQuery - Last executed query: ', self.cursor._last_executed)
  return ret

Tags: inselfexecutedef时间connectionthispid
1条回答
网友
1楼 · 发布于 2024-10-03 13:24:43

上面的示例一直失败,因为我试图在仍在处理长时间运行的查询的同一mysql线程上执行“KILL PID”查询。“KILL PID”是在长时间运行的查询完成之后才运行的,这不是我想要的。长话短说,终止长时间运行的查询的方法是打开另一个连接,用kill PID终止长时间运行的查询。现在,在执行长时间运行的查询之前,获取正确的PID是非常重要的。你知道吗

最初,我编写了一个类,它初始化了一个连接和游标,并且可以在函数中的任何位置进行访问。我没有这样做,而是编写了一个函数,可以在调用时为我创建连接。我为长时间运行的查询和kill query函数初始化了一个连接。我从长时间运行的查询中获得了进程ID,然后使用一个定时线程在一定时间后启动“KILL PID”。你知道吗

以下是一个框架/大部分代码:

class QueryWithTimeout(object):
  def __init__(self, db, query, totalTimeout):
    self.db = db
    self.query = query
    self.totalTimeout = totalTimeout
    ...

  def setUpConnection(self):
    connection = connections[self.db]
    cursor = connection.cursor()
    return cursor, connection

  def getProcessId(self, cursor):
    processID = 'SELECT CONNECTION_ID();'
    cursor.execute(processID)
    processIDOutput = cursor.fetchall()[0]
    return processIDOutput[0]

  def killDBConnection(self, processId, ret):
    killCursor, killConnection = self.setUpConnection()
    killQuery = 'KILL {pId};'.format(pId=processId)
    try:
      killCursor.execute(killQuery)
    except:
      print('TEMP')

  def executeTimedQuery(self, pId, cursor):
    ret = {...}
    timeoutCall = Timer(self.totalTimeout, self.killDBConnection, [pId, ret])
    timeoutCall.start()
    try:
      cursor.execute(self.query)
      #timeoutCall.cancel()
    except:
      return ret
  ret[...] = ...
  return ret

  def processTimedQuery(self):
    queryCursor, queryConnection = self.setUpConnection()
    queryProcessId = self.getProcessId(queryCursor)
    return self.executeTimedQuery(queryProcessId, queryCursor)

顺便说一句,我尝试了各种各样的方法,但都失败了,但这次失败了。你知道吗

相关问题 更多 >