shashantrika
shashantrika

Reputation: 1089

how to schedule a task with start time and end time using java Timer and TimerTask

Hi im developing some schedular which should start at a particular time and it should stop after some time.. starting after a delay i can do using timer and timerTask classes.. But stopping i dont have much idea. How to stop the timer after a elapsed time.

Upvotes: 1

Views: 1851

Answers (1)

jrochette
jrochette

Reputation: 1117

If you run your task in a thread, you can keep a reference to the Future object of the task and set a timeout. Something like that :

Future<?> future = executor.submit(new customTask()));
try {
    future .get(timeout, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
    // The timeout exception is thrown when the get times out. Handle your stop logic here
}

You might want to handle the InterruptedException, ExecutionException and TimeoutException separately.

You can also call the .cancel() method on the Future object when your stop timer expires, but I recall reading somewhere that it is not recommanded

Upvotes: 3

Related Questions