Reputation: 5567
I have an application in Java where I need to schedule a TimerTask
which will be executed after 500ms , however if a certain event occurs, I must reset the timer for this task (so that we must wait another 500ms for it to execute). I have a timer
declared for the whole class. I use the following code:
public static void main(String[] args) {
if (curr_pck == my_pck) {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
myTask();
}
}, 500);
}
}
public static void myTask() {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
myTask();
}
}, 500);
//EXECUTE CODE WHICH ISN'T RELEVANT TO THE QUESTION
}
I know that if I use timer.cancel()
I can't reuse the timer object, however I thought reinitialising it in the line timer = new Timer()
should solve this issue. Is there any way around this?
EXCEPTION on line timer.schedule(new TimerTask() {
inside myTask()
function:
java.lang.IllegalStateException: Timer already cancelled.
Upvotes: 3
Views: 1008
Reputation: 31
Create a class Timerr with the appropriate methods. Then access it as if it were a normal timer.
public class Timerr
{
private Timer timer;
public Timerr()
{
timer = new Timer();
start();
}
public void start()
{
timer.schedule(new TimerTask()
{
@Override
public void run()
{
System.out.println("hi");
}
}, 500);
}
public void reset()
{
timer.cancel();
timer.purge();
start();
}
}
Create instance
private Timerr timer = new Timerr();
Do your reset
if(condition)
{
timerr.reset();
}
Upvotes: -1
Reputation: 30
You may want to check out Java's Swing timer. It works somewhat differently and you may have to write an internal class or an actionlistener, but the Swing timer includes .stop() and .restart(), which seem like they would work better in your application.
Upvotes: -2