假设我有一个任务,从java.util.concurrent.BlockingQueue中提取元素并处理它们。
public void scheduleTask(int delay, TimeUnit timeUnit)
{
scheduledExecutorService.scheduleWithFixedDelay(new Task(queue), 0, delay, timeUnit);
}如果频率可以动态改变,我如何调度/重新安排任务?
发布于 2009-10-05 09:58:20
我不认为你能改变固定利率延迟。我认为您需要使用附表()来执行一次操作,并在完成后再进行一次调度(如果需要,可以使用修改的超时时间)。
发布于 2009-10-05 10:31:05
使用schedule(Callable<V>, long, TimeUnit)而不是scheduleAtFixedRate或scheduleWithFixedDelay。然后确保您的可调用在将来的某个时刻重新安排自身或一个新的可调用实例。例如:
// Create Callable instance to schedule.
Callable<Void> c = new Callable<Void>() {
public Void call() {
try {
// Do work.
} finally {
// Reschedule in new Callable, typically with a delay based on the result
// of this Callable. In this example the Callable is stateless so we
// simply reschedule passing a reference to this.
service.schedule(this, 5000L, TimeUnit.MILLISECONDS);
}
return null;
}
}
service.schedule(c);这种方法避免了关闭和重新创建ScheduledExecutorService的需要。
发布于 2018-10-10 17:20:48
我最近不得不使用ScheduledFuture来完成这个任务,并且不想包装可运行的或类似的东西。我就是这样做的:
private ScheduledExecutorService scheduleExecutor;
private ScheduledFuture<?> scheduleManager;
private Runnable timeTask;
public void changeScheduleTime(int timeSeconds){
//change to hourly update
if (scheduleManager!= null)
{
scheduleManager.cancel(true);
}
scheduleManager = scheduleExecutor.scheduleAtFixedRate(timeTask, timeSeconds, timeSeconds, TimeUnit.SECONDS);
}
public void someInitMethod() {
scheduleExecutor = Executors.newScheduledThreadPool(1);
timeTask = new Runnable() {
public void run() {
//task code here
//then check if we need to update task time
if(checkBoxHour.isChecked()){
changeScheduleTime(3600);
}
}
};
//instantiate with default time
scheduleManager = scheduleExecutor.scheduleAtFixedRate(timeTask, 60, 60, TimeUnit.SECONDS);
}https://stackoverflow.com/questions/1519091
复制相似问题