Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 563
Praveen Avatar asked Dec 28 '22 04:12

Praveen


1 Answers

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(); 
like image 112
Pablo Santa Cruz Avatar answered Jan 08 '23 22:01

Pablo Santa Cruz