Is there anyway to Trigger an action by local time?

Armin Mashhadi :

I know it may seems easy but i'm really new on Java , So i need your help.

I want to use local time (Mill Seconds) to trigger an action, for example printing "Hello world". More specific, Print "Hello world" at "13:10:30:300" . but i don't know what specific class should i use (Data,Local Time , etc) so i can compare it to Desired Time in a while loop. I tried this, but it's not working on milliseconds.

import java.time.format.DateTimeFormatter;  
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss:ms");  
     LocalDateTime now = LocalDateTime.now();  
     LocalDateTime desire = 13:10:30.300;
     while (now != desire ) {
         LocalDateTime now = LocalDateTime.now();
     }
     System.out.println("Hello World!");

Do you have any suggestion please?

Lazar Petrovic :

Your main problem is this: now != desire. This compares whether these objects are the same, not whether their contents are the same. To compare if the times are the same, you should use now.equals(desire).

Your second problem is that this this loop might become infinite if between 2 checks now becomes greater than desire.

Your third problem is that you are wasting CPU cycles constantly checking the time. You should calculate how many milliseconds your desired time is away and sleep until then. So something like: Thread.sleep(desireMillis - nowMillis)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=361389&siteId=1