try:
    client.connect('localhost', 4444)
except:
    print('ERROR: Could not connect to MQTT')
client.on_connect = on_connect
client.on_message = on_message
startTime = time.time()
waitTime = 5
while True:
    client.loop()
elapsedTime = time.time() - startTime
if elapsedTime > waitTime:
    client.disconnect()
break
Python MQTT Connect only for a limited time