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
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();