What is the equivalent of javascript setTimeout in Java?

JavaJavascriptTimerSettimeoutSetinterval

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

Use Java 9 CompletableFuture, every simple:

CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS).execute(() -> {
  // Your code here executes after 5 seconds!
});

Solution 3 - Java

> "I used the Timer class, but I think that that is not the best way."

The other answers assume you are not using Swing for your user interface (button).

If you are using Swing then do not use Thread.sleep() as it will freeze your Swing application.

Instead you should use a javax.swing.Timer.

See the Java tutorial How to Use Swing Timers and Lesson: Concurrency in Swing for more information and examples.

Solution 4 - Java

Using the java.util.Timer:

new Timer().schedule(new TimerTask() {
	@Override
	public void run() {
		// here goes your code to delay
	}
}, 300L); // 300 is the delay in millis

Here you can find some info and examples.

Solution 5 - Java

You can simply use Thread.sleep() for this purpose. But if you are working in a multithreaded environment with a user interface, you would want to perform this in the separate thread to avoid the sleep to block the user interface.

try{
	Thread.sleep(60000);
	// Then do something meaningful...
}catch(InterruptedException e){
	e.printStackTrace();
}

Solution 6 - Java

Do not use Thread.sleep as it will freeze your main thread, and not simulate setTimeout from JS.

You need to create and start a new background thread to run your code without stoping the execution of the main thread.

One example:


    new Thread() {
        @Override
        public void run() {
            try {
                this.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            
            // your code here

        }
    }.start();

Solution 7 - Java

public ScheduledExecutorService = ses;
ses.scheduleAtFixedRate(new Runnable() {
    run() {
            //running after specified time
    }
}, 60, TimeUnit.SECONDS);

It runs after 60 seconds from scheduleAtFixedRate. Check the ScheduledExecutorService documentation.

Solution 8 - Java

You should use Thread.sleep() method.

try {

    Thread.sleep(60000);
    callTheFunctionYouWantTo();
} catch(InterruptedException ex) {

}

This will wait for 60,000 milliseconds(60 seconds) and then execute the next statements in your code.

Solution 9 - Java

There is setTimeout() method in underscore-java library.

Code example:

import com.github.underscore.Underscore;
import java.util.function.Supplier;

public class Main {

    public static void main(String[] args) {
        final Integer[] counter = new Integer[] {0};
        Supplier<Void> incr =
            () -> {
                counter[0]++;
                return null;
            };
        Underscore.setTimeout(incr, 0);
    }
}

The function will be started in 100ms with a new thread.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAr&#243;n Garc&#237;a S&#225;nchezView Question on Stackoverflow
Solution 1 - JavaOleg MikhailovView Answer on Stackoverflow
Solution 2 - Javauser1079877View Answer on Stackoverflow
Solution 3 - JavaDavidPostillView Answer on Stackoverflow
Solution 4 - JavaLuca PinelliView Answer on Stackoverflow
Solution 5 - JavaAman GautamView Answer on Stackoverflow
Solution 6 - JavaJuliano MoraesView Answer on Stackoverflow
Solution 7 - JavababakView Answer on Stackoverflow
Solution 8 - JavaAditya SinghView Answer on Stackoverflow
Solution 9 - JavaValentyn KolesnikovView Answer on Stackoverflow