Search code examples
pythontimepython-requestspaho

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.

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.

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

Solution

  • 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()