【发布时间】:2019-06-18 00:06:30
【问题描述】:
我目前正在使用 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()
有人知道我做错了什么吗?
【问题讨论】:
标签: python multithreading server mqtt