javaandroidandroid-handlerpostdelayed

code to be executed every x milliseconds, changeable


I have a code to be executed every x milliseconds, where x is changeable during the app life cycle.

Right now I use the postDelayed function of an handler, but I am not able to manage the situation when the delay changes.

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // do some staff

        handler.postDelayed(this, x);
    }
}, x);   

My problem is that in other parts of the app the x value can change, and I need to execute the code in the run function instantly after the change, and continue with the infinite execution of the delayed code (with new value of x).


Solution

  • Save a reference to your Runnable and keep the delay as class variable like this:

    private Long x = 1000L;
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            // do some staff
            handler.postDelayed(this, x);
        }
    }
    

    then

    handler.post(r);
    

    to kick it off.

    Then create a setter and getter for x that takes care of the change:

    setX(Long: value){ 
        if(x != value){
            x = value
            handler.removeCallbacks(r);
            //run immediately
            handler.post(r);
        }
    }
    
    getX(){ return x };