jeet.chanchawat
jeet.chanchawat

Reputation: 2575

With each successive call to this `timerMethod` , timerInt's value increases faster than before

I am working on an app, which gets a sort of restart with an event. On the first run, the timer works perfect (1sec = 1 increment). but, on next run (1sec = 2 increment) on third run (1sec = 4 increment) and so on... I think there is something wrong with the new TimerTask object being created. but, dunno how to handle it. any suggestion or alternate ?

CODE SNIPPET:

Timer t = new Timer();

void timerMethod()
    {
      t.schedule(new TimerTask() {
      public void run() {
                timerInt++;
                //TODO bug in timer in consecutive runs. To confirm, see log
                Log.d("timer", "timer " + timerInt);
                /*  runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        timerDisplayPanel.setText( timerInt + " Sec");
                    }
                });*/
            }
        }, 1000, 1000);

    }

Upvotes: 0

Views: 150

Answers (2)

Makis Arvanitis
Makis Arvanitis

Reputation: 1195

The snippet you provided is working properly

  • 1 sec 1 increment
  • 2 sec 2 increment
  • 3 sec 3 increment

etc

So probably the problem is somewhere else in your code.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500675

It sounds like you're calling timerMethod() multiple times.

When you've called it three times, you've got three timer tasks scheduled - so they'll all fire each second, and all increment timerInt. You either need to not call it multiple times, or cancel the existing timer tasks before adding more.

If that's not the case, please provide a short but complete program to show what's happening. The context is fairly vague at the moment.

Upvotes: 2

Related Questions