Python线程无法同时工作

时间:2019-01-24 09:42:04

标签: python multithreading server mqtt

我目前正在使用python,希望通过MQTT接收数据,然后将其发送到服务器。当我收到“ 0”时,我想启动一个计时器,该计时器应在后台运行,这样我仍然可以获取数据并将其发送到服务器。我使用线程启动计时器,但就我而言,程序会停止运行直到计时器结束,然后继续接收和发送。

代码:

import threading
import time
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
     client.subscribe("test/test/projekt")

def timer_started():
     global timer_thread
     print("timer started")
     shutdown_timer = time.time()
     elapsed = 0
     while elapsed < 5:
          elapsed = time.time()-shutdown_timer
     print("Timer finished")

def on_message(client, userdata,msg):
     global thread_active 
     if msg.payload =="0" and thread_active == False:
           thread_active =True
           global timer_thread
           timer_thread.start()

timer_thread = threading.Thread(target=timer_started)
client=mqtt.CLient()
client.on_connect() = on_connect
client.on_message= on_message
client.connect("test.mosquitto.org",1883,60)
client.loop_forever()

有人知道我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

变量thread_active和msg.payload的比较可能是罪魁祸首。比较之前,MQTT有效负载需要转换为字符串。我对上面的代码进行了检查,并进行了修改,使其可以在计时器线程中接收数据。

下面是工作示例:

import threading
import time
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print('connection')
    print (rc)
    client.subscribe("Test")

def timer_started():
    global timer_thread, thread_active
    print("timer started")
    shutdown_timer = time.time()
    elapsed = 0
    while elapsed < 5:
        elapsed = time.time()-shutdown_timer
    print("Timer finished")
    thread_active =False

def on_message(client, userdata,msg):
    print("Message")
    print(msg.payload)
    global thread_active
    if msg.payload.decode("utf-8") =="0" and thread_active == False:
        thread_active =True
        global timer_thread
        timer_thread.start()


timer_thread = threading.Thread(target=timer_started)
thread_active = False
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost",1883,60)
client.loop_forever()

在将虚拟主题'Test'值发布为'0'时,计时器启动,并且在运行计时器进行检查时,将'5'发布到同一主题。下面是预期运行的输出:

connection
0
Message
b'0'
timer started
Message
b'5'
Timer finished