drcross
drcross

Reputation: 85

How can I ensure the timeliness of a callback function in Python?

I have a callback function but the delegate that issues the callback occasionally takes several seconds to provides updates (because it is waiting for data over a remote connection). For my use case this is troublesome because I need to run a function at a regular time, or quit the program. What is the easiest way to have a timer in python that runs a function, or quits the application if I haven't had an update from the delegate within a certain space of time, like five seconds?


def parseMessage(client, userdata, message): # CALLBACK FUNCTION THAT LISTENS FOR NEW MESSAGES
    signal = int(str(message.payload.decode("utf-8")))
    writeToSerial(signal)

def exceptionState():  # THIS IS THE FUNCTION I WOULD LIKE TO RUN IF THERE'S NO CALLBACK
    print("ERROR, LINK IS DOWN, DISABLING SERVER")
    exit()

def mqttSignal():                
    client.on_message = parseMessage # THIS INVOKES THE CALLBACK FUNCTION
    client.loop_forever()

Upvotes: 2

Views: 482

Answers (1)

g.d.d.c
g.d.d.c

Reputation: 48028

This sounds like a good scenario for setting up a background thread that exits if you don't get an event based on a sentinel value. A simple implementation might look like this:

from datetime import datetime, timedelta
from threading import Thread
from time import sleep

class Watcher:
  timeout = timedelta(minutes=5)

  def __init__(self):
    self.last_signal = datetime.now()
    Thread(target=self.exception_state).start()

  def parse_message(self):
    self.last_signal = datetime.now()
    # Other handling code here

  def exception_state(self):
    while True:
      if datetime.now() - self.last_signal > self.timeout:
        exit("No signal received.")
      sleep(5)

Upvotes: 3

Related Questions