简体   繁体   English

为什么“ time.sleep”不延迟MQTT发布消息?

[英]Why isn't “time.sleep” delaying the MQTT publish messages?

Python 2.7 Python 2.7

I want to publish 3 times and interval=3 sec. 我想发布3次,间隔= 3秒。

So I try to use time.sleep(3) , then publish. 所以我尝试使用time.sleep(3) ,然后发布。

My code is like: 我的代码是这样的:

for i in range(3):
    print(i)
    mqttc.publish("test", "hello")
    time.sleep(3)

The result should be like: 结果应为:

0
(Publish)
(delay 3 sec)
1
(Publish)
(delay 3 sec)
2
(Publish)
(delay 3 sec)

But real result is: 但是实际结果是:

0
(delay 3 sec)
1
(delay 3 sec)
2
(delay 3 sec)
(Publish)
(Publish)
(Publish)

The real result is found from MQTT.fx and Python subscribe. 真正的结果是从MQTT.fx和Python订阅中找到的。

Delay is normal worked to "Print", but "Publish" not, 延迟正常可用于“打印”,但不能“发布”,

I don't understand why publish is continuous... 我不明白为什么发布是连续的...

It's quite simple: MQTT needs to have its event loop running to process network communications. 这非常简单:MQTT需要运行其事件循环以处理网络通信。 By sleeping the thread you effectively wrestle control away from MQTT and keep it from doing anything useful. 通过使线程处于休眠状态,您可以有效地使控制权脱离MQTT,并使它无法做任何有用的事情。

Instead of blocking the thread, you should let MQTT's event loop handle timing: 而不是阻塞线程,您应该让MQTT的事件循环处理计时:

for i in range(3):
    print(i)
    mqttc.publish("test", "hello")
    mqttc.loop(timeout=3.0)

You can also run a background event loop on a different thread, using loop_start() and loop_stop() but threads are not a cheap resource so if you'd be instead wasting a whole thread on doing literally nothing, it's better to let that thread be useful instead. 您还可以使用loop_start()loop_stop()在不同的线程上运行后台事件循环,但是线程并不是便宜的资源,因此,如果您浪费整个线程而实际上不做任何事情,最好让该线程而是有用的。 The rule of thumb with threads is that if with one thread you had one problem, with two threads you have two or more problems (they tend to multiply). 线程的经验法则是,如果一个线程遇到一个问题,而两个线程遇到两个或更多问题(它们趋于成倍增加)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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