4

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.

Praveen
  • 90,477
  • 74
  • 177
  • 219

3 Answers3

7

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(); 
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • if i schedule a new task then the previous scheduler stops/kills its process?? – Praveen Dec 08 '10 at 14:33
  • It depends on how you use it. – Pablo Santa Cruz Dec 08 '10 at 14:33
  • how to do that?when i shutdown the scheduler object. i can not schedule an another task for that same object? – Praveen Dec 08 '10 at 14:36
  • `scheduler.schedule()` returns a `Future` object, all you have to do is remember the `Future` and use it's `cancel()` method to remove a single task from the `Executor`, you can then schedule a new task. You don't have to create a new `Executor` every time. Just cancel the old task and schedule a new task when the button is clicked. – Reboot Dec 08 '10 at 14:49
2

As long as they are not declared as final, just create new instances.

codelark
  • 12,254
  • 1
  • 45
  • 49
1

There is also Quartz API for this purpose. It would give you more flexibility in clustered env.

Vinay Lodha
  • 2,185
  • 20
  • 29