0

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);

    }
jeet.chanchawat
  • 5,842
  • 5
  • 38
  • 59

2 Answers2

2

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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.

Makis Arvanitis
  • 1,175
  • 1
  • 11
  • 18