There is an equivalent of javascript setTimeout function in java

Question:

I am implementing a function in java that must necessarily wait a while, similar to javascript's setTimeout, which executes a piece of code after a defined time has elapsed.

For example the following javascript code:

setTimeout(function(){ alert("Hello"); }, 3000);

For now the closest I've seen is creating a thread and pausing it:

thread.sleep

but I would like to know if there is a simpler way.

Answer:

You can use the Handler class

new Handler().postDelayed(new Runnable() {
        public void run() {

          //***Aquí agregamos el proceso a ejecutar.

        };
    }, 3000); //Cada 3 segundos

or the Timer class:

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        //***Aquí agregamos el proceso a ejecutar.

    }
}, 3000); //Cada 3 segundos

Using Java 9 you can make use of the CompletableFuture class:

CompletableFuture.delayedExecutor(3, TimeUnit.SECONDS).execute(() -> {
  //***Aquí agregamos el proceso a ejecutar.
});
Scroll to Top