Python:时间段后停止循环

Python: Stop Loop After Time Period

我时常遇到问题,我的 python 脚本将停止 运行 并且我将停止将数据点添加到数据库,我只想制作脚本 运行 10 分钟,每 10 分钟一个 cron 作业将启动一个新实例。

我下面的代码在 10 分钟后无法停止,我的 python 体验以分钟为单位,所以我确信这对于经验丰富的 Python 编码员来说是显而易见的,在此先感谢。

#! /usr/bin/env python

import json
import paho.mqtt.client as mqtt
import requests
import sys
import time

max_time = 600 # 10 mins
start_time = time.time()

def on_connect(client, userdata, flags, rc):
  client.subscribe("zigbee2mqtt/0x0015bc001b238abc")

def on_message(client, userdata, msg):
  requests.post("http://www.url.uk/rpc", data = msg.payload.decode())
  if (time.time() - start_time) < max_time:
    client.loop_stop()
    
client = mqtt.Client()
client.connect("localhost",1883,60)

client.on_connect = on_connect
client.on_message = on_message

client.loop_forever()

来自您正在使用的库的 github issue

if you need to quit the program after a certain period of not receiving any messages, you might try something like this:

from paho.mqtt.client import Client
import time
client = Client()
client.connect(broker, port)
client.loop_start()
run = True
TIMEOUT = 10  # seconds
while run:
    client._msgtime_mutex.acquire()
    last_msg_in = client._last_msg_in
    client._msgtime_mutex.release()
    now = time.monotonic()
    if now - last_msg_in > TIMEOUT:
        client.disconnect()
        client.loop_stop()
        run = False
    else:
        time.sleep(1)

在您的情况下,计时器可以设置为 10*60 秒,您可以避免使用 loop_forever() 函数。

最后我是这样实现的:

#! /usr/bin/env python

import json
import paho.mqtt.client as mqtt
import requests
import sys
import time

max_time = 600 # 10 mins
start_time = time.time()  # remember when we started

def on_connect(client, userdata, flags, rc):
  client.subscribe("zigbee2mqtt/0x0015bc001b238abc")

def on_message(client, userdata, msg):
  if (time.time() - start_time) > max_time:
    client.loop_stop()
    client.disconnect()
    print("Script Ended: Ran For " + str(time.time() - start_time) + " seconds, limit was " + str(max_time))
  else:
    requests.post("http://www.url.uk/rpc", data = msg.payload.decode())
    
client = mqtt.Client()
client.connect("localhost",1883,60)

client.on_connect = on_connect
client.on_message = on_message

client.loop_forever()