Checking threads for a while
I am creating a thread for my application that will perform an exit operation at a specific time (only hours and minutes, day / month does not matter). Is this the correct way to do it, and also the correct way to check the time? I test for 24 hours, not AM / PM by the way.
I'll then in another class call it something like new topic (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
}
}
}
}
a source to share
You might want to count currentTime
in the cycle while
: -)
Instead of waiting 10 seconds before checking the end condition, you can determine the millimeters that correspond to your end and wait for the number of millimeters between the end time and the end time.
If your end time is between 235950 and 235959, you risk losing it.
Update
You can define the number of millis to wait like this:
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;
Note that you need to compute this in the while loop as well, since the hibernation can be interrupted, the next iteration will take less timeToSleep.
a source to share
To test, you must enter two things: "sleep" and "clock". They can be in the same interface if you want, or separately. A production implementation will be simple to use Thread.sleep
and System.currentTimeMillis
, but that means you can also create fake implementations that make the code testable.
a source to share