假设我有一个任务,是拉动因素从一个java。工具.并行。BlockingQueue和处理它们。

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

怎么我可以安排/重新安排任务,如果频率可以改变的动态?

  • 这个想法是采取一流的数据的更新和传播它们,在批GUI
  • 用户应当能够有所不同频率的更新
有帮助吗?

解决方案

我不认为你可以改变一个固定的速率延迟。我认为你需要使用 时间表() 执行一次,并计划再一次就已经完成了(一修改的时间,如果需要的话)。

其他提示

使用 schedule(Callable<V>, long, TimeUnit) 而不是 scheduleAtFixedRatescheduleWithFixedDelay.然后确保你可调用 重新安排本身或一个新的可调用的实例 在某一点的未来。例如:

// 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.

你不是应该使用 scheduleAtFixedRate 如果你们试图要处理的几个队的任务与特定的间隔时间? scheduleWithFixedDelay 只会等待指定的延迟和随后执行一个任务的队列。

在任何一种情况下, schedule* 方法中的一个 ScheduledExecutorService 将返回 ScheduledFuture 参考。如果你想改变的速率,可以取消 ScheduledFuture 并重新安排的任务有不同的速率。

scheduleWithFixedDelay(...)返回RunnableScheduledFuture.为了重新安排它的,你可能只是取消和重新安排。重新安排它的,你可能只包RunnableScheduledFuture智慧的一种新的可运行的:

new Runnable() {
    public void run() {
        ((RunnableScheduledFuture)future).run();
    }
};

我不得不这样做,最近使用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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top