Java Reference
In-Depth Information
public class DelayedJob implements Delayed {
private final Instant scheduledTime;
String jobName;
public DelayedJob(String jobName, Instant scheduledTime) {
this.scheduledTime = scheduledTime;
this.jobName = jobName;
}
@Override
public long getDelay(TimeUnit unit) {
// Positive delay means it should stay in queue. Zero or negative delay
// means that it ready to be removed from the queue.
long delay = MILLIS.between(Instant.now(), scheduledTime);
// Convert the delay in millis into the specified unit
long returnValue = unit.convert(delay, MILLISECONDS);
return returnValue;
}
@Override
public int compareTo(Delayed job) {
long currentJobDelay = this.getDelay(MILLISECONDS);
long jobDelay = job.getDelay(MILLISECONDS);
int diff = 0;
if (currentJobDelay > jobDelay) {
diff = 1;
}
else if (currentJobDelay < jobDelay) {
diff = -1;
}
return diff;
}
@Override
public String toString() {
String str = "(" + this.jobName + ", " + "Scheduled Time: " +
this.scheduledTime + ")";
return str;
}
}
The program in Listing 12-25 shows how to use the DelayedJob objects as elements in a DelayQueue . It adds
three jobs (“Print Data”, “Populate Data”, and “Balance Data”) to the queue that are scheduled to run 9m, 3m, and 6000
seconds after the current time on your computer, respectively. Note the sequence of adding these jobs in the queue. I
have not added the job to be run first as the first element. It is the job of the DelayQueue to arrange the elements in its
queue based on their delay time returned from their getDelay() method. When you run this program, there will be a
delay of about 3 seconds because no elements will be expired and the take() method on the queue will be blocked.
When elements start expiring, you will see them getting removed one by one by the take() method in the while-loop.
You may get a different output when you run the program.
Search WWH ::




Custom Search