3

When I use Handler and its postDelayed method, the run() method executes twice. Below is part of my code.

Handler deneme = new Handler();

deneme.postDelayed(new Runnable() {

            @Override
            public void run()
            {
                randomOyna();
            }
        }, 1000);

where randomOyna is the method

public void randomOyna()
{   
    Log.v("sonOlarak", "çalıştı");
}

I monitor the LogCat and see that "çalıştı" entry is written twice, so that randomOyna is called twice. The task is scheduled truely, but executes both after 1 sec and 2 secs.

  • Don't have much experience with these but I assume you've checked the runnable definition code isn't running twice? – Genesis Nov 28 '11 at 17:53
  • The code that you have posted seems to be correct, without knowing where you run that code it's impossible to figure out what's going on. – gwvatieri Nov 28 '11 at 17:57
  • as @gwa said , and i add that you should make sure if you didnt add your log somwhere on your Code source – Houcine Nov 28 '11 at 18:01

1 Answers1

0

Use this class instead and check to see if it is running already first:

public class Timer {

private java.util.Timer timer;

public synchronized void schedule(final TimerTask timerTask, long delay) {
    stop();
    timer=new java.util.Timer();
    timer.schedule(new TimerTask(){

        @Override
        public void run() {
            timerTask.run();
            timer = null;
        }},delay);
}

public synchronized void stop() {
    if(timer!=null) {
        timer.cancel();
        timer.purge();
        timer = null;
    }   
}

public synchronized void scheduleAtFixedRate(TimerTask timerTask, long delay, long period) {
    stop();
    timer=new java.util.Timer();
    timer.scheduleAtFixedRate(timerTask, delay, period);
}

public boolean isRunning() {
    return timer!=null;
}   

}

Paul Nikonowicz
  • 3,883
  • 21
  • 39