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)
如果可以动态更改频率,如何安排/重新安排任务?
Ada*_*ski 28
使用schedule(Callable<V>, long, TimeUnit)而不是scheduleAtFixedRate或scheduleWithFixedDelay.然后确保您的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.
我最近不得不使用 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)
| 归档时间: |
|
| 查看次数: |
14381 次 |
| 最近记录: |