What is the equivalent of javascript setTimeout in Java?

前端 未结 9 871
梦毁少年i
梦毁少年i 2020-12-13 06:23

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条回答
  • 2020-12-13 06:51

    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.

    0 讨论(0)
  • 2020-12-13 06:55

    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.

    0 讨论(0)
  • 2020-12-13 06:57
    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

    0 讨论(0)
提交回复
热议问题