简体   繁体   English

重复延迟的任务n次

[英]Repeat delayed task n times

i want to run a portion of code n times with delay of some seconds. 我想以几秒钟的延迟运行部分代码n次。

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. 问题: for循环可同时运行所有任务。 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 我发现我的问题的逻辑非常接近: -Bukkit在For循环内延迟了任务

but doesn't looks relevant to me 但看起来与我无关

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM