'Receive the time now in an updated manner
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?
Solution 1:[1]
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);
}}
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Phil Freihofner |
