I have the following problem that the standard library doesn’t solve well, and I’m wondering if anybody has seen another library out there than can do it so I don’t need to hack together a custom solution. I have a task that is currently scheduled on a thread pool using scheduleWithFixedDelay(), and I need to modify the code to handle requests for “urgent” execution of the task related to asynchronous events. Thus, if the task is scheduled to occur with a delay of 5 minutes between executions, and an event occurs 2 minutes after the last completed execution, I would like to execute the task immediately and then have it wait for 5 minutes after the completion of the urgent execution before it runs again. Right now the best solution that I can come up with is to have the event handler call cancel() on the ScheduledFuture object returned by scheduleWithFixedDelay() and execute the task immediately, and then set a flag in the task to tell it to reschedule itself with the same delay parameters. Is this functionality available already and I’m just missing something in the documentation?
I have the following problem that the standard library doesn’t solve well, and I’m
Share
If you are using
ScheduledThreadPoolExecutorthere is a methoddecorateTask(well in fact there are two, for Runnable and Callable tasks) that you can override to store a reference to the task somewhere.When you need urgent execution, you just call
run()on that reference which makes it run and rescheduled with same delay.A quick hack-up 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 like this:
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 produces the following output:
06
08
10
11
13
15