具有可变延迟的ScheduledExecutorService

par*_*rkr 20 java concurrency executorservice blockingqueue

假设我有一个从java.util.concurrent.BlockingQueue中提取元素并处理它们的任务.

public void scheduleTask(int delay, TimeUnit timeUnit)
{
    scheduledExecutorService.scheduleWithFixedDelay(new Task(queue), 0, delay, timeUnit);
}
Run Code Online (Sandbox Code Playgroud)

如果可以动态更改频率,如何安排/重新安排任务?

  • 我们的想法是获取数据更新流并将它们批量传播到GUI
  • 用户应该能够改变更新的频率

Ada*_*ski 28

使用schedule(Callable<V>, long, TimeUnit)而不是scheduleAtFixedRatescheduleWithFixedDelay.然后确保您的Callable 在将来的某个时刻重新安排自己或新的Callable实例.例如:

// 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);
Run Code Online (Sandbox Code Playgroud)

这种方法避免了关闭和重新创建的需要ScheduledExecutorService.


Bri*_*new 7

我认为你不能改变固定费率延迟.我认为您需要使用schedule()执行一次性操作,并在完成后再次安排(如果需要,可以修改超时).


Chi*_*ata 6

我最近不得不使用 ScheduledFuture 来执行此操作,并且不想包装 Runnable 等。我是这样做的:

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);
}
Run Code Online (Sandbox Code Playgroud)