4

I'm trying to execute a chunk of Java code in my Android program every two seconds. My code currently looks like this:

       LinearLayout.postDelayed(new Runnable() { 
            public void run() { 

            //Do stuff here

            } 
       }, 2000);

Unfortunately, this only runs once after two seconds and then never runs again. How could I get it to run every two seconds?

Thanks in advance for all your help.

josmo
  • 41
  • 1
  • 1
  • 4

4 Answers4

3

Try this:

   LinearLayout.postDelayed(new Runnable() { 
        public void run() { 

        //Do stuff here

            // assuming LinearLayout is enclosing class
            LinearLayout.this.postDelayed(this, 2000);
        } 
   }, 2000);
Peter Knego
  • 79,991
  • 11
  • 123
  • 154
0
 new Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            // Enter your code which you want to execute every 2 second
        }
    }, 0, 2000);//put here time 1000 milliseconds = 1 second
Nirav Bhavsar
  • 2,133
  • 2
  • 20
  • 24
0

Put your code in a loop. Or you could look into Alarms.

Haphazard
  • 10,900
  • 6
  • 43
  • 55
0

you can try a timer

Here is another example

Ronnie
  • 11,138
  • 21
  • 78
  • 140