Home > database >  Receive the time now in an updated manner
Receive the time now in an updated manner

Time:05-11

I am performing an operation in Java code, this is the code I am performing:

public String GetTheTimeNow() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
   LocalDateTime now = LocalDateTime.now();
 return dtf.format(now);
}

And I want the return in function to run every second so that the discussion is always updated. how do I do it?

CodePudding user response:

Another way apart from what Phil Freihofner mentioned, call your GetTheTimeNow() from calling method & use Thread.sleep:

public class Test {
public static void main(String[] args) throws Exception {
    for (;;) {
        System.out.println(new Test().GetTheTimeNow());
        Thread.sleep(1000);
    }       
}

public String GetTheTimeNow() {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
    LocalDateTime now = LocalDateTime.now();
    return dtf.format(now);
}}

CodePudding user response:

There are three different "timers" that can be launched: javax.swing.Timer, java.util.Timer, or java.util.concurrent.ScheduledExecutorService.

With each you can schedule a task to execute periodically.

CodePudding user response:

And thanks to all the helpers, I just can not give likes yet, as soon as I can I will give you!

  •  Tags:  
  • java
  • Related