init 初始化定时器
# # 创建定时器线程
self.timer_interval = 1
self.publish_message_timer = threading.Timer(interval=self.timer_interval, function=self.publish_message)
函数
#发布监测消息
def publish_message(self):
print(self.publist_monitor_topic)
info = [
{
"id": "mos_num",
"value": "30",
"remark": ""
},
{
"id": "mos_switch",
"value": "2",
"remark": ""
},
{
"id": "mos_temp",
"value": "3",
"remark": ""
}]
msg = json.dumps(info)
result = self.client.publish(self.publist_monitor_topic, msg)
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{self.publist_monitor_topic}`")
else:
print(f"Failed to send message to topic {self.publist_monitor_topic}")
self.publish_message_timer = threading.Timer(interval=self.timer_interval, function=self.publish_message) # 每1秒钟启动一次run函数.不是下面的t启动的
self.publish_message_timer.start()
使用定时器
if self.publish_message_timer.is_alive():
self.publish_message_timer.cancel()
print("定时器处于启动状态,终止定时器")
self.publish_message_timer = threading.Timer(interval=self.timer_interval,
function=self.publish_message)
print("启动定时器")
self.publish_message_timer.start()