简体   繁体   中英

Python Thread is not working simultaniously

I'm currently working with python and want to receive data via MQTT and later send it to a server. When I receive a "0" then I want to start a timer, which should run in the background so I still can get data and send it to a server. I start the timer with a thread but in my case the program stops till the timer is over and then continues with the receive and send.

Code:

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

Does somebody know what I'm doing wrong?

The variable thread_active and comparison of msg.payload might be the is culprit. MQTT payload needs to be converted to string before comparing it. I did a check for the above code with modification it could receive data while in timer thread.

Below is the working example:

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

On publishing the dummy topic 'Test' value with '0', timer gets started and during the timer run for a check, '5' is published to the same topic. Below is the output as expected to run:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM