Timer task in java?

I need to do timertask in java. Scenario: I have to schedule a task for some delay in general. If I clicked the button, it will cancel the current timer and then reschedule it. How to implement it in java?

when I used cancel() , I can no longer access the timer. that is, I cannot reuse this object. I declared Timer and Timertask static.

Thanks at Advance.

+4
source share
3 answers

The easiest way I can come up with is to use Executor .

Suppose you want to schedule a task to run in 30 seconds:

 ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.schedule(new Task(), 30, TimeUnit.SECONDS); 

Task should be a class that implements the Runnable interface:

 class Task implements Runnable { public void run() { // do your magic here } } 

If you need to execute to stop the execution of your task, you can use the shutdownNow method:

 // prevents task from executing if it hasn't executed yet scheduler.shutdownNow(); 
+7
source

Until they are declared final , just create new instances.

+2
source

For this purpose also Quartz API . This will give you great flexibility in a clustered env.

+1
source

All Articles