2010-01-23 3 views
8

흥미로운 question을 다음과 같이 반복적 인 작업을 위해 ScheduledThreadPoolExecutor를 사용하고 있습니다.자바에서 실행 가능한 작업 예약하기

이 개체를 예약하면 다음 작업 실행을 취소하는 데 사용할 수있는 ScheduledFuture 개체가 반환됩니다. 여기에서 주목해야 할

한 가지

SomeTask task = new SomeTask(); 

그래서 작업 자체가 일정 인식하지 어디에 - 작업 자체가 완전히 schedule--

ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); 
ScheduledFuture nextSchedule = 
    executor.schedule(task, 60000, TimeUnit.MILLISECONDS); 

에서 분리된다. 작업을 취소하고 자체 일정을 새로 작성하는 방법이 있다면 알려주십시오.

감사

+1

btw 적어도 사용자가 수락 한 답변을 업 보트하는 것이 일반적입니다 ("이 답변은 유용합니다"는 상향 투표 아이콘의 제목입니다.) – Bozho

+0

감사합니다 bozho, 지적했다. – bushman

답변

7

작업이 ScheduledExecutorService를 참조하고 필요한 경우 다시 실행 자체를 예약 할 수없는 이유가 없다 : 그것은 그것으로 조작을 할 수 있도록,

// (Need to make variable final *if* it is a local (method) variable.) 
final ScheduledExecutorService execService = Executors.newSingleThreadScheduledExecutor(); 

// Create re-usable Callable. In cases where the Callable has state 
// we may need to create a new instance each time depending on requirements. 
Callable<Void> task = new Callable() { 
    public Void call() { 
    try { 
     doSomeProcessing(); 
    } finally { 
     // Schedule same task to run again (even if processing fails). 
     execService.schedule(this, 1, TimeUnit.SECONDS); 
    } 
    } 
} 
+0

@adamski, 이건 정말 대단한 것으로 밝혀졌습니다. – bushman

4

이 작업에 executor 전달 :

SomeTask task = new SomeTask(executor); 
+0

이것이 나에게 일어 났음에 틀림 없다. 감사합니다. bozho – bushman