Java 中 javascript setTimeout 的等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26311470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:11:59  来源:igfitidea点击:

What is the equivalent of javascript setTimeout in Java?

javajavascripttimersettimeoutsetinterval

提问by Arón García Sánchez

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.

我需要实现一个在单击按钮 60 秒后运行的函数。请帮忙,我使用了 Timer 类,但我认为这不是最好的方法。

采纳答案by DavidPostill

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

“我使用了 Timer 类,但我认为这不是最好的方法。”

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

其他答案假设您没有将 Swing 用于您的用户界面(按钮)。

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

如果你正在使用的Swing那么就不能使用Thread.sleep(),因为它会冻结你的Swing应用程序。

Instead you should use a javax.swing.Timer.

相反,您应该使用javax.swing.Timer.

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

有关更多信息和示例,请参阅 Java 教程如何使用 Swing 计时器课程:Swing 中的并发性

回答by Aditya Singh

You should use Thread.sleep()method.

你应该使用Thread.sleep()方法。

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.

这将等待 60,000 毫秒(60 秒),然后执行代码中的下一条语句。

回答by Aman Gautam

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.

您可以简单地Thread.sleep()用于此目的。但是,如果您在具有用户界面的多线程环境中工作,您可能希望在单独的线程中执行此操作以避免睡眠阻塞用户界面。

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

回答by Valentyn Kolesnikov

There is setTimeout()method in underscore-javalibrary.

underscore-java库中有setTimeout()方法。

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.

该函数将在 100 毫秒内使用新线程启动。

回答by Oleg Mikhailov

Asynchronous implementation with JDK 1.8:

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:

使用 lambda 表达式调用:

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 timeoutexpires and runnableexecutes.

在主线程中谨慎使用它 - 它会在调用后挂起一切,直到timeout过期并runnable执行。

回答by Juliano Moraes

Do not use Thread.sleepor 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. Like this:

不要使用,Thread.sleep否则它会冻结您的主线程并且不会从 JS 模拟 setTimeout。您需要创建并启动一个新的后台线程来运行您的代码,而不会停止主线程的执行。像这样:

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


        // your code here

    }
}.start();

回答by babak

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

它在 scheduleAtFixedRate https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html60 秒后运行

回答by user1079877

Use Java 9 CompletableFuture, every simple:

使用 Java 9 CompletableFuture,每一个简单:

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

回答by Luca Pinelli

Using the java.util.Timer:

使用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

Hereyou can find some info and examples.

在这里您可以找到一些信息和示例。