Ivan Kuckir
Ivan Kuckir

Reputation: 2549

Android - Timer class

I am making an android app (QR code reader) and I need to do some action 4 times a second. I decided to use Timer class for this purpose. I discovered a strange behavior of it:

timer = new Timer();
timer.scheduleAtFixedRate(onTimer, 100, stn.GetStep());
timer.cancel();
timer = new Timer();
timer.scheduleAtFixedRate(onTimer, 100, stn.GetStep());

The last line throws an error - java.lang.IllegalStateException: TimerTask is scheduled already. Isn't it weird?

Upvotes: 1

Views: 1068

Answers (2)

aioobe
aioobe

Reputation: 420991

No, that's how it is supposed to work. A TimerTask is a one-off object. Create a new TimerTask if you want to schedule the code again. (See the documentation.)

If you dislike the idea of creating a completely new object each run, you can do something like

Runnable toRunRepeatedly = new Runnable() {
    public void run() {
        // your code goes here...
    }
};

and then do

TimerTask tt = new TimerTask() {
    public void run() {
        // Delegate to the same runnable each time.
        toRunRepeatedly.run();
    }
};

Related question:

Upvotes: 3

Quintin B
Quintin B

Reputation: 5881

SHORT ANSWER: No, not it's not weird.

It is a thread and it would be in the 'canceling' state, but due to the quick execution of the statements, the thread would not be cancelled yet. So it's not really weird, welcome to threading 101.

Why are you cancelling the thread to re-invoke it? What purpose does this serve? You are not giving the first instance time to safely stop before you call it again. You may want to set the timer object to null before re-creating it.

Upvotes: 0

Related Questions