开发者

How can I prevent getting an exeption when canceling an already canceled Timer(because some times it's already canceled/done with it)?

I tried to cancel a Timer.schedule() when I start a new one. Because I need 1 sechedule at once. But I get this exception

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Timer already cancelled.

As you can see the Timer is already canceled, how can I prevent that? I tried this code, still didn't work check it please:

Note: Everything in this code works fine except the 2nd line

Public void startTimer(byte h, byte m) {
    timer.cancel();//cancel the Timer whenever I start a new one
    Date d = new Date();
    d.setHours(h);
    d.setMinutes(m);
    d.setSeconds(0);
    UserInterface.setAlarmTime(h, m);
    timer.schedule(new Alarm(), d);

If I remove the 2nd line this code will give me a Timer but I doesn't can开发者_开发百科cel the old Timer so whenver I call this method I get more timers. And this is not what I really need.

So how can I prevent this Exception? There's no methods in the Timer class that will tell me if there's a Timer in schedule, already checked it. So please help me.


try
{
    timer.cancel();
}

catch (IllegalStateException e)
{
    // Log error
}


This is expected, because you can't call schedule() on a cancelled timer. If you're going to cancel the existing timer, you'll need to create a new one before you can schedule another task:

public void startTimer(byte h, byte m) {
    timer.cancel();
    timer = new Timer();
    // ...


I think the problem is happening because you are cancelling the timer and then scheduling it again.

If you look at the Timer.java source code, here are two interesting methods --

 public void cancel() {
    synchronized(queue) {
          thread.newTasksMayBeScheduled = false;
        queue.clear();
        queue.notify();  // In case queue was already empty.
      }
}

And then the sched method --

 synchronized(queue) {
          if (!thread.newTasksMayBeScheduled)
              throw new IllegalStateException("Timer already cancelled.");

You should modify your code to not use the same Timer object to cancel and then schedule.. instead create a new Timer.

http://www.docjar.com/html/api/java/util/Timer.java.html


Just cancel the timer. Instantiate a new one and schedule it.

timer.cancel();
timer = new Timer();
Date d = ... // set the date
timer.schedule (new Alarm(d));

That said, your method name implies something different that what you are doing, which is really a setSchedule.


Or other idea is to have global variable which is boolean. So first time you have set up the timer, the value becomes TRUE

if wasTimerSetup
 {
   timer.cancel();
 }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜