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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With