Search code examples
javaandroidmultithreadinghandlerrunnable

The effects of firing off a runnable multiple times using a Handler


I have simple runnable like so

private Runnable runnable = new Runnable()
{
    @Override
    public void run()
    {
        someVariable = true;
    }
};

I use it with a Handler and delay like this

handler.postDelayed(runnable, 60000);

if this functionality gets spammed and the above is called repeatedly it adds runnable multiple times to the message queue.

if this is the case is there away to check if there is one in the message queue first before adding another?


Solution

  • Hi the way I do is to remove the messages and callbacks after my handler runs once. A simple example of my code would be

    final Handler handler = new Handler();
    
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Log.d("runnable", "handler invoked just once");
                handler.removeCallbacksAndMessages(null);
            }
        };
    
        handler.postDelayed(runnable, 2000);
        handler.postDelayed(runnable, 2000); // demo: if this is called multiple times my runnable code wont run