为了账号安全,请及时绑定邮箱和手机立即绑定

Python 线程不能同时工作

Python 线程不能同时工作

哆啦的时光机 2021-10-19 15:10:46
我目前正在使用 python 并希望通过 MQTT 接收数据,然后将其发送到服务器。当我收到“0”时,我想启动一个计时器,它应该在后台运行,这样我仍然可以获取数据并将其发送到服务器。我用一个线程启动计时器,但在我的情况下,程序停止直到计时器结束,然后继续接收和发送。代码:import threadingimport timeimport paho.mqtt.client as mqttdef 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_connectclient.on_message= on_messageclient.connect("test.mosquitto.org",1883,60)client.loop_forever()有人知道我做错了什么吗?
查看完整描述

1 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

变量 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()

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


connection

0

Message

b'0'

timer started

Message

b'5'

Timer finished


查看完整回答
反对 回复 2021-10-19
  • 1 回答
  • 0 关注
  • 301 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号