重复延迟任务n次

时间:2018-03-30 05:30:49

标签: java android postdelayed

我希望运行一部分代码n次,延迟几秒钟。

这是我的代码:

 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
    }

问题: for循环同时运行所有任务。我想逐个延迟执行任务。

我在帖子上找到了答案: - Repeat a task with a time delay?

但它重复工作无限次。

我发现我的问题非常接近逻辑: - Bukkit Delayed Task Inside a For Loop

但看起来并不适合我

3 个答案:

答案 0 :(得分:0)

你可以试试这个,

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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