ioana ioana - 2 months ago 23
Python Question

publish a message every 10 seconds mqtt

I am new to mqtt and still discovering this interesting protocol.
I want to create a client in python that publishes every 10 seconds a message. Until now I succeed to publish only one message and keep the client connected to the broker.

How can I make the publishing part a loop ?

Below is my client:

import mosquitto
mqttc=mosquitto.Mosquitto("ioana")
mqttc.connect("127.0.0.1",1884,60,True)
mqttc.publish("test","Hello")
mqttc.subscribe("test/", 2)

while mqttc.loop() == 0:
pass


Thanks.

Answer

You can sleep between calls:

import mosquitto
import time # import time module
mqttc=mosquitto.Mosquitto("ioana")
mqttc.connect("127.0.0.1",8000,60,True)
mqttc.subscribe("test/", 2)
while mqttc.loop() == 0:
    mqttc.publish("test","Hello")
    time.sleep(10)# sleep for 10 seconds before next call
Comments