0

i want to run a portion of code n times with delay of some seconds.

here is my code:

 Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.e("myLog","Runnable()-->Run()");
               // do a task here
        }
    };

Handler handler = new Handler();
    // loop repeating task 6 times
    for (int count = 0; count < 6; count++){
        Log.e("Log","Task loop "+count);

        handler.postDelayed(runnable, 20000);    // run task after 20 seconds
    }

Problem: the for loop running all the tasks concurrently. i want to run delayed task one by one.

i found a answer at post :- Repeat a task with a time delay?

but it repeating job infinite times.

i found very close logic to my question:- Bukkit Delayed Task Inside a For Loop

but doesn't looks relevant to me

3 Answers3

1
// Instance variable

private int counter = 0;
private int maxCounter = 6;

createTask(){
    if(counter<maxCount){
        counter++;
        handler.postDelayed(runnable, 20000);
    }
}


Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.e("myLog","Runnable()-->Run()");
               // do a task here

               createTask();
            } catch (IOException e) {
                Log.e("myLog "+e.toString());
            }
        }
    };
Subir Kumar Sao
  • 8,171
  • 3
  • 26
  • 47
  • 1
    tried this code, if im using runnable.run() job only ran once, when i used handler.postDelayed(runnable,20000) the job repeated 4 time then stopped – Harshit Panchal Mar 30 '18 at 07:00
1
 import java.util.Timer;
 import java.util.TimerTask;
 import java.util.concurrent.TimeUnit;
 class RepeatableTask extends TimerTask{
    int repeats;
    Timer time;
    public RepeatableTask(int repeats){
        this.repeats=repeats;
    }
    void init(){
        time = new Timer();
        time.schedule(this,0,TimeUnit.MINUTES.toMillis(delayInMinutes));
    }
    void stop(){
        time.cancel();
    }
    void run(){
        if(repeats == 0){stop();}
        new Thread->{
            //task
        }
        repeats--;
    }
}

//usage
RepeatableTask taskObject = new RepeatableTask(5);
taskObject.init();
  • i cant understand why these codes running the task two times more then given, if i pass 10 in RepeatableTask's constructor it run the task 12 times – Harshit Panchal Apr 09 '18 at 14:24
0

You can try this,

        int n=0;
        myHandler=new Handler();
        myRunnable=new Runnable() {
            @Override
            public void run() {
                //do your task
                n++;
                if(n<=count)
                    myHandler.postDelayed(this,2000);


            }
        };
        myRunnable.run();
Jyoti JK
  • 2,141
  • 1
  • 17
  • 40