Hi there :) I'm making a thread for my application that's going to do an exit operation at a given time (only hours and minutes, day/month doesn't matter). Is this the right way to do it, and also the right way to test for time? I'm testing for a 24 hour clock by the way, not AM / PM.
I'm then in another class going to call this something like new Thread(new ExitThread()).start();
public class ExitThread implements Runnable {
public long getDate() {
Date thisdate = new Date(System.currentTimeMillis());
return thisdate.getTime();
}
public long exitDate() {
Date exitdate = new Date(System.currentTimeMillis());
exitdate.setHours(23);
exitdate.setMinutes(30);
exitdate.setSeconds(0);
return exitdate.getTime();
}
public long sleepTime() {
Calendar cal = Calendar.getInstance();
long now = cal.getTime().getTime();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long endMillis = cal.getTime().getTime();
long timeToSleep = endMillis - now;
return timeToSleep;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(sleepTime());
} catch (InterruptedException e) {
e.printStackTrace();
}
if (getDate() >= exitDate()) {
// System exit method here
}
}
}
}