Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for specific date. Calendar Java Code Optimization

I want to perform a task using Java at specific, given hour. My code works, but it doesn't look good. I'm comparing two strings. I tried to compare dates using getTimeInMills() but numbers aren't the same.

Here's my code:

import java.util.Calendar;

class Voter {
Calendar current,deadline;
boolean keepGoing = true;

public static void main(String[] args) {
    Voter strzal = new Voter();
    strzal.shoot();
}

public void shoot() {
    deadline = Calendar.getInstance();
    deadline.set(2011,6,21,11,20,00);

    while (keepGoing) {
        // wait 1 second
        try {
            Thread.sleep(1000);
            System.out.print(".");
        } catch (InterruptedException ex) { ex.printStackTrace(); }

        current = Calendar.getInstance();

        if (deadline.getTime().toString().equals(current.getTime().toString())) {
            System.out.println("Got it!");
            keepGoing = false;
        } // end of if
    } // end of while
} // end of shoot() method

}

I'm running in the loop, waiting for the current time to be equal to deadline (in an example I set it to 21st July 2011 11:10 AM).

How can I improve my code? I'd like to use for example compareTo() or getTimeInMills() method from Calendar class, but I can't set deadline properly.

Thanks in advance.

like image 818
Khozzy Avatar asked Aug 07 '26 14:08

Khozzy


1 Answers

Use a ScheduledExecutorService to manage this for you, rather than sleeping and waiting for the right time. The schedule method sounds like it'll do what you need.

like image 110
Jeff Foster Avatar answered Aug 10 '26 11:08

Jeff Foster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!