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:
imp开发者_StackOverflow中文版ort 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.
Using a ScheduledExecutorService is a better suggestion, however for your knowledge
Calendar deadline = Calendar.getInstance();
deadline.set(2011,6,21,11,20,00);
long endTime = deadline.getTime().getTime();
// later
long current = System.currentTimeMillis();
if (current >= endTime) {
System.out.println("Got it!");
break;
}
Don't reinvent the wheel! There's a JDK class for this - the ScheduledThreadPoolExecutor. Here's one line of code that does it all:
new ScheduledThreadPoolExecutor(1).schedule(new Runnable() {
public void run() {
// Do something
}
}, 1, TimeUnit.HOURS);
This example waits 1 hour, but you can replace that with so many seconds or whatever you need.
Job done.
精彩评论