How to execute a function every two seconds in Java on Android?

27,322

Try this:

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

        //Do stuff here

            // assuming LinearLayout is enclosing class
            LinearLayout.this.postDelayed(this, 2000);
        } 
   }, 2000);
Share:
27,322
Admin
Author by

Admin

Updated on July 28, 2022

Comments

  • Admin
    Admin almost 2 years

    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.