What is the equivalent of javascript setTimeout in

2020-02-07 19:07发布

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.

9条回答
Explosion°爆炸
2楼-- · 2020-02-07 19:09
public ScheduledExecutorService = ses;
ses.scheduleAtFixedRate(new Runnable(){
    run(){
            //running after specified time
}
}, 60, TimeUnit.SECONDS);

its run after 60 seconds from scheduleAtFixedRate https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

查看更多
时光不老,我们不散
3楼-- · 2020-02-07 19:09

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.

查看更多
Anthone
4楼-- · 2020-02-07 19:12

Use Java 9 CompletableFuture, every simple:

CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS).execute(() -> {
  // Your code here executes after 5 seconds!
});
查看更多
男人必须洒脱
5楼-- · 2020-02-07 19:15

"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.

查看更多
女痞
6楼-- · 2020-02-07 19:15

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.

查看更多
放我归山
7楼-- · 2020-02-07 19:21

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

Code example:

import com.github.underscore.U;
import com.github.underscore.Function;

public class Main {

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

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

查看更多
登录 后发表回答