Harshit Panchal
Harshit Panchal

Reputation: 81

Repeat delayed task n times

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

Upvotes: 0

Views: 2380

Answers (3)

MarshallWalpole
MarshallWalpole

Reputation: 26

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

Upvotes: 1

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8401

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

Upvotes: 1

Jyoti JK
Jyoti JK

Reputation: 2171

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

Upvotes: 0

Related Questions