سؤال

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(); 

نصائح أخرى

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

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top