我如何不断地在X个线程之间进行迭代

时间:2019-01-22 16:08:40

标签: python multithreading python-2.7

我正在读取1到4个设备,并且我连接到每个设备并启动线程来读取数据。 我想创建一个运行线程unit1,unit2等然后再开始的while循环。我所有人都需要设置一个计时器,每5秒读取一次所有设备的信息。

我的代码可以读取和发送数据,但我在理解如何创建while循环以永久读取单位方面遇到问题。

thread_list = []
ports = ['/dev/ttyXRUSB0']
for item in ports:
  #setup conection  
  client = EPsolarTracerClient(method = 'rtu', port = item, baudrate = 115200, timeout = 0.2 )
  #client = ModbusClient(method = 'rtu', port = item, baudrate = 115200, timeout = 0.2 )
  client.connect()
  #read config from device
  epstime = client.read_rtc()
  sync_date = datetime.datetime.now()

  #write config to device
  client.write_rtc(sync_date)

  #create and start thread for device
  thread = threading.Thread(target=readunit,args=(client,))
  thread_list.append(thread)
  thread.start()
  # below is just leftover from old code but it is where i want to start the loop 
while client.connect:
  # readunit(client) # old code

   sleepTime = 5

   sleep(sleepTime)

我需要每X秒运行每个线程。并重复 永远.. 例如

线程1 线程2 .... 睡眠x秒。 重复

1 个答案:

答案 0 :(得分:0)

我建议创建2个单独的函数并对其进行线程化,然后使用Timer函数在5秒钟后调用它们,像这样,

from threading import *
import time

def function1():
    while(True):
        print "1"
        time.sleep(5) # wait 5 seconds      

def function2():
    while(True):
        print "2"
        time.sleep(5) # wait 5 seconds

# create threads
t = Timer(5.0, function1) # start the thread after 5 seconds
t2 = Timer(5.0, function2)