开发者

Timer Task in java?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜