我有以下问题,标准库不能很好地解决,我想知道是否有人见过另一个库可以做到这一点,所以我不需要拼凑一个自定义解决方案。我有一个当前使用 scheduleWithFixedDelay() 在线程池上安排的任务,我需要修改代码以处理“紧急”执行与异步事件相关的任务的请求。因此,如果任务计划在两次执行之间延迟 5 分钟发生,并且在上次完成执行后 2 分钟发生事件,我想立即执行任务,然后让它在完成后等待 5 分钟再次运行之前的紧急执行。现在我能想到的最好的解决方案是让事件处理程序在 scheduleWithFixedDelay() 返回的 ScheduledFuture 对象上调用 cancel() 并立即执行任务,然后在任务中设置一个标志以告诉它重新安排自己具有相同的延迟参数。此功能是否已经可用,我只是在文档中遗漏了一些内容?
最佳答案
如果您正在使用 ScheduledThreadPoolExecutor 有一个方法 decorateTask(实际上有两个,用于 Runnable 和 Callable 任务)您可以重写以存储对某处的任务。
当您需要紧急执行时,您只需对该引用调用 run() 即可使其以相同的延迟运行和重新安排。
快速破解尝试:
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();
}
}
可以这样使用:
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);
}
}
并产生以下输出: 06 08 10 11 13 15
关于java - ScheduledThreadPoolExecutor scheduleWithFixedDelay 和 "urgent"执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1401520/