If you are using ScheduledThreadPoolExecutor , there is a decorateTask method (there are actually two, for Runnable and Callable tasks) that you can override to store a reference to the task somewhere.
When you need urgent execution, you simply call run() on this link, which forces it to run and transfer with the same delay.
Quick hack attempt:
public class UrgentScheduledThreadPoolExecutor extends
ScheduledThreadPoolExecutor {
RunnableScheduledFuture scheduledTask;
public UrgentScheduledThreadPoolExecutor (int corePoolSize) {
super (corePoolSize);
}
@Override
protected RunnableScheduledFuture decorateTask (Runnable runnable,
RunnableScheduledFuture task) {
scheduledTask = task;
return super.decorateTask (runnable, task);
}
public void runUrgently () {
this.scheduledTask.run ();
}
} which can be used as follows:
public class UrgentExecutionTest {
public static void main (String [] args) throws Exception {
UrgentScheduledThreadPoolExecutor pool = new UrgentScheduledThreadPoolExecutor (5);
pool.scheduleWithFixedDelay (new Runnable () {
SimpleDateFormat format = new SimpleDateFormat ("ss");
@Override
public void run () {
System.out.println (format.format (new Date ()));
}
}, 0, 2L, TimeUnit.SECONDS);
Thread.sleep (7000);
pool.runUrgently ();
pool.awaitTermination (600, TimeUnit.SECONDS);
}
} and displays the following result: 06 08 10 11 13 15
vtrubnikov
source share