가변 지연이있는 ScheduleDexecutorService
-
19-09-2019 - |
문제
java.util.concurrent.blockingqueue에서 요소를 가져오고 처리하는 작업이 있다고 가정 해 봅시다.
public void scheduleTask(int delay, TimeUnit timeUnit)
{
scheduledExecutorService.scheduleWithFixedDelay(new Task(queue), 0, delay, timeUnit);
}
주파수를 동적으로 변경할 수있는 경우 작업을 예약 / 재조정하려면 어떻게해야합니까?
- 아이디어는 데이터 업데이트 스트림을 취하고 GUI로 배치로 전파하는 것입니다.
- 사용자는 업데이트 빈도를 변경할 수 있어야합니다.
해결책
고정 속도 지연을 변경할 수 있다고 생각하지 않습니다. 나는 당신이 사용해야한다고 생각합니다 일정() 원샷을 수행하고 완료된 후 다시 예약하십시오 (필요한 경우 수정 된 시간 초과).
다른 팁
사용 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
.
사용해서는 안됩니다 scheduleAtFixedRate
특정 간격으로 여러 큐 작업을 처리하려는 경우? scheduleWithFixedDelay
지정된 지연 만 기다린 다음 큐에서 하나의 작업을 실행합니다.
두 경우 모두 schedule*
a 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);
}