简体   繁体   English

Python:时间段后停止循环

[英]Python: Stop Loop After Time Period

I am having problems where every now and them my python script will cease to run and i'll stop getting data points added to the db, i want to make the script only run for 10 mins and every 10 mins a cron job will start a new instance.我现在遇到问题,我的 python 脚本将停止运行,我将停止将数据点添加到数据库中,我想让脚本只运行 10 分钟,每 10 分钟一个 cron 作业将启动一个新实例。

My code below fails to stop after 10 mins, my python experience is measured in minutes so i'm sure its something obvious to a seasoned Python coder, thanks in advance.我下面的代码在 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()

From a github issue of the library you are using:来自您正在使用的库的github 期

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)

In your case, the timer can be set to 10*60 seconds and you can avoid using the loop_forever() function.在您的情况下,计时器可以设置为 10*60 秒,您可以避免使用loop_forever() function。

This is how i achieved it in the end:这就是我最终实现它的方式:

#! /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()

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

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