Search code examples
androidrunnableandroid-handlerpostdelayed

How the method postDelayed(Runnable runnable, Long delayMilliSeconds) works exactly?


I want to know when the method postDelayed(...) is executed and there are many messages that are waiting in the message queue. In that case, when the runnable will be runned ? is it gonna be after the time defined in the method elapses ? or it will wait until its role come in the message queue? or what... ?


Solution

  • Let's check the source code and documentation:

    Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached. The time-base is uptimeMillis(). Time spent in deep sleep will add an additional delay to execution.

    public final boolean postDelayed(Runnable r, long delayMillis) {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }
    

    Now let's check sendMessageDelayed:

    Enqueue a message into the message queue after all pending messages before (current time + delayMillis).

    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
    

    So, postDelayed add your task to be executed after all pending messages but before uptime + the delay that you put.

    Check this question for more explanation: Does postDelayed cause the message to jump to the front of the queue?

    Hope that it helps.