如何为专用调度睡眠专用的python线程?

时间:2013-04-12 02:48:08

标签: python multithreading function scheduled-tasks sleep

我正在编写一个库,它将连接到套接字并管理它们,处理它们的数据,然后根据它做一些事情。

我的问题在于每20秒向套接字发送b“\ r \ n \ x00”。我想如果我为ping函数启动了一个新线程,那就行了。

..但是,time.sleep()似乎暂停了整个程序而不是我认为只是那个帖子。

到目前为止,这是我的代码:

def main(self):
  recvbuf = b""
  self.connect(self.group, self.user, self.password)
  while self.connected:
    rSocket, wSocket, error = select.select([x[self.group] for x in self.conArray], [x[self.group] for x in self.conArray], [x[self.group] for x in self.conArray], 0.2) #getting already made socket connections
    for rChSocket in rSocket:
      while not recvbuf.endswith(b"\x00"): #[-1] doesnt work on empty things... and recvbuf is empty.
        recvbuf += rChSocket.recv(1024) #need the WHOLE message ;D
      if len(recvbuf) > 0:
        dataManager.manage(self, self.group, recvbuf)
        recvbuf = b""
    for wChSocket in wSocket:
      t = threading.Thread(self.pingTimer(wChSocket)) #here's what I need to be ran every 20 seconds.
      t.start()
  x[self.group] for x in self.conArray.close()

这是pingTimer函数:

def pingTimer(self, wChSocket):
  time.sleep(20)
  print(time.strftime("%I:%M:%S %p]")+"Ping test!") #I don't want to mini-DDoS, testing first.
  #wChSocket.send(b"\r\n\x00")

谢谢:D

1 个答案:

答案 0 :(得分:1)

此:

t = threading.Thread(self.pingTimer(wChSocket))

不按预期行事。它在同一个线程中调用self.pingTimer并将返回值传递给threading.Thread。那不是你想要的。你可能想要这个:

t = threading.Thread(target=self.pingTimer, args=(wChSocket,))