I have to do the timertask in java. The scenario is: I have to schedule a task for some delay intially. If i have clicked a button it will cancel the current Timer and then it will reschedule it. How to implement it in java?
when i have used the cancel() i can not access the timer again. that is i can not reuse that object. i have declared the Timer and Timertask as static. 
Thanks in Advance.
The easiest way I can think of implementing that is using an Executor.
Let's say you want to schedule a task to run in 30 seconds:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(new Task(), 30, TimeUnit.SECONDS);
Task must be a class implementing Runnable interface:
class Task implements Runnable
{
    public void run()
    {
        // do your magic here
    }
}
If you need to halt execution of your task, you can use shutdownNow method:
// prevents task from executing if it hasn't executed yet
scheduler.shutdownNow(); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With