N 초마다 정기적으로 작업 (파일 다운로드)을 시작해야하는 시스템을 개발 중입니다. 이것은 내가 다음과 같이 Timer
및 Timertask
를 사용하여 한 문제가되지 않습니다 :정기적으로 실행하지만 일정 시간 동안 타이머를 시작하는 방법
FileTimer rXMLFileTimer;
private static Timer timer = new Timer("FileReader");
rXMLFileTimer = new ReadFileTimer();
int myDelay = 30;
timer.scheduleAtFixedRate(rXMLFileTimer, 0, myDelay * 1000);
및 rXMLFileTimer.cancel()
가 호출 될 때까지 timertask
가 실행됩니다. 지금까지 문제 없음.
이제 rXMLFileTimer.cancel()
가 또는 주어진 시간을 호출 될 때까지이 timertask
실행해야한다는 요구되고있다. 타임 아웃이 발생 후 내가 timerTask.cancel()
를 호출 할 수 없기 때문에이 작동하지 않습니다
public class Test {
public static class MyJob implements Callable<ReadFileTimer> {
@Override
public ReadFileTimer call() throws Exception {
Timer timer = new Timer("test");
ReadFileTimer t = new ReadFileTimer();
int delay = 10;
// Delay in seconds
timer.schedule(t, 0, delay * 1000);
return t;
}
}
public static void main(String[] args) {
MyJob job = new MyJob();
System.out.println(new Date());
Future<ReadFileTimer> control = Executors.newSingleThreadExecutor().submit(job);
ReadFileTimer timerTask = null;
try {
int maxAmountOfTime = 30;
timerTask = control.get(maxAmountOfTime, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
control.cancel(true);
} catch (InterruptedException ex) {
} catch (ExecutionException ex) {}
}
}
다음과 같이
내 첫 번째 방법은 (작동하지 않았다)을 Future
을 구현하는 것이 었습니다. 그렇다면 제 질문은 : 주어진 시간 동안 timerTask
을 어떻게 시작할 수 있습니까?
감사합니다.
감사합니다. 이것은 내가 시도했던 것보다 훨씬 쉽다. – Luixv