Search code examples
javaandroidfor-loopcountdowntimer

How to loop through timer class for delayed time?


I want run timer for about 30000 ms and up to 8 or more times each so here is my loop but it runs all timers at once after 30000ms

    public void repeatTimerTask() {
    repeat = 8; // need to run 30 sec timer for 8 times but one after one

    startTimer(30000); // firsat timer for 30 sec

    Handler handler = new Handler();
    for (int a = 1; a<=repeat; a++) {

        final int finalA = a;
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                startTimer(30000);

            }

        }, 30000); // delay until to finish first timer for 30 sec
    }
}

Solution

  • To run a timer for n seconds you can use CountDownTimer

    Declare two varibales globbaly. One for number of times you want to repeat. and one to keep the count of repetaion.

     private int NUM_REPEAT = 4;
     private int REPEAT_COUNT = 0;
    

    Then call this method wherever you want. One thing to note if you want to run this loop 5 times you have to give number of repeation 4. Cause to satrt this function you have to call it so that will not come in count.

    private void startTimer() {
    
        new CountDownTimer(3000, 1000) {
            int secondsLeft = 0;
    
            public void onTick(long ms) {
                if (Math.round((float) ms / 1000.0f) != secondsLeft) {
                    secondsLeft = Math.round((float) ms / 1000.0f);
                    // resend_timer is a textview
                     resend_timer.setText("remaining time is "+secondsLeft);
                    ;
                }
            }
    
            public void onFinish() {
                Log.d(TAG, "timer finished "+REPEAT_COUNT);
                if (REPEAT_COUNT <= NUM_REPEAT) {
                    startTimer();
                    REPEAT_COUNT++;
                }
    
            }
        }.start();
    }