user1950349 user1950349 - 1 year ago 61
Java Question

print hello world only when conditions are met

I want to print out

"Hello World"
only when both the below conditions are true;

  • If current hour is greater than or equal to 8PM.

  • And if
    becomes true. This is coming from another service, basically this is to check whether some process finished or not.

Otherwise I will keep sleeping until both the above conditions become true. Below is the code I have:

public static void main(String[] args) {
DateTime dt = new DateTime();
int hour = dt.getHourOfDay();
if (hour < 20) {
TimeUnit.HOURS.sleep(20 - hour);

boolean isDone = checkStatus();
while (!isDone) {
isDone = checkStatus();

// now print out
System.out.println("Hello World");

As you can see, I have two different conditions separately which does the check and then at the end I print out. Is there any better way to write above code to accomplish same thing?

It doesn't have to be exactly accurate. I am calling
method every 15 minutes to see whether
became true or not.

Answer Source

There is a bug in the application, where if it happens to be after 8 AM, but the checkStatus doesn't return true before midnight, then it will continue executing during the day.

Put both conditions inside the loop together:

boolean isDone = false;
while (!isDone) {
    int hour = new DateTime().getHourOfDay();
    isDone = hour >= 20;
    if (!isDone) TimeUnit.HOURS.sleep(20 - hour);

    isDone = checkStatus();
    if (!isDone) TimeUnit.MINUTES.sleep(15);

System.out.println("Hello World");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download