What is the equivalent of javascript setTimeout in Java?

Arón García Sánchez picture Arón García Sánchez · Oct 11, 2014 · Viewed 66.1k times · Source

I need to implement a function to run after 60 seconds of clicking a button. Please help, I used the Timer class, but I think that that is not the best way.

Answer

Oleg Mikhailov picture Oleg Mikhailov · Apr 25, 2016

Asynchronous implementation with JDK 1.8:

public static void setTimeout(Runnable runnable, int delay){
    new Thread(() -> {
        try {
            Thread.sleep(delay);
            runnable.run();
        }
        catch (Exception e){
            System.err.println(e);
        }
    }).start();
}

To call with lambda expression:

setTimeout(() -> System.out.println("test"), 1000);

Or with method reference:

setTimeout(anInstance::aMethod, 1000);

To deal with the current running thread only use a synchronous version:

public static void setTimeoutSync(Runnable runnable, int delay) {
    try {
        Thread.sleep(delay);
        runnable.run();
    }
    catch (Exception e){
        System.err.println(e);
    }
}

Use this with caution in main thread – it will suspend everything after the call until timeout expires and runnable executes.