title: mqtt: avoid buffering of messages
body: <p>Right now I am sitting on a project, where a python script subscribes to a topic on the broker and waits for a message. When a message is received the script takes some actions and shows an image for about 5 seconds. To this point everything works. </p>
  
  <p>The problem I am struggling with is that when a message comes in while the function is already executing, the function gets directly executed again after it finishes. For example: If 3 messages get published directly one after another, the function gets called one after another, showing three times the image.</p>
  
  <p>The behaviour I want to achieve is that messsages which get published while the function is already executing are ignored.</p>
  
  <p>This link (<a href="http://www.steves-internet-guide.com/loop-python-mqtt-client/" rel="nofollow noreferrer">http://www.steves-internet-guide.com/loop-python-mqtt-client/</a>) says that: </p>
  
  <blockquote>
    <p>When new messages arrive at the Python MQTT client they are placed in
    a receive buffer.</p>
    
    <p>The messages sit in this receive buffer waiting to be read by the
    client program.</p>
  </blockquote>
  
  <p>I think that's the problem! But I don't understand how I can avoid this buffering behaviour.</p>
  
  <p>Like suggested I tried playing around with setting flags etc but this doesn't worked.</p>
  
  <p>For a better understanding I wrote a simple script which prints <code>1, 2, 3, 4, 5</code> when a message is published</p>
  
  <pre><code>#!/usr/bin/env python
  
  import os, os.path
  import time
  import subprocess
  import paho.mqtt.client as mqtt
  
  mqtt_username = "user"
  mqtt_password = "password"
  mqtt_topic = "Topic"
  
  def on_connect(client, userdata, flags, rc):
      client.subscribe(mqtt_topic)
  
  def on_message(client, userdata, msg):
      print('1')
      time.sleep(1)
      print('2')
      time.sleep(1)
      print('3')
      time.sleep(1)
      print('4')
      time.sleep(1)
      print('5')
      time.sleep(1)
      print('---')
  
  client = mqtt.Client()
  
  client.on_connect = on_connect
  client.on_message = on_message
  
  client.username_pw_set(mqtt_username, mqtt_password)
  client.connect("localhost", 1883, 60)
  client.loop_forever()
  </code></pre>
  
  <p>The messages are getting published with this command:</p>
  
  <pre><code>mosquitto_pub -d -u user -P password -t Topic -m "Hello"
  </code></pre>
  
  <p>Publishing one message everything is fine. Publishing three messages directly one after another results in this output:</p>
  
  <pre><code>1
  2
  3
  4
  5
  ---
  1
  2
  3
  4
  5
  ---
  1
  2
  3
  4
  5
  ---
  </code></pre>
  
  <p>But it should result in this output, ignoring the other two messages:</p>
  
  <pre><code>1
  2
  3
  4
  5
  ---
  </code></pre>