简体   繁体   中英

Java - Run tasks in varying time intervals

This question is for a college assignment.
I want to run a block of code every n*2 seconds (eg wait 1 second and run and wait 2 seconds and run and wait 4 seconds and run, etc) up to 5 times.

I currently have something like this.

int timer = 1000;
int tryCounter = 0;

while( !condition()  && counter < 5){
  doTask();
  Thread.sleep(timer);
  timer *= 2;
  counter++;
}

Although this works, my grade benefits from not using Thread.sleep() . I figured out using a ScheduledThreadPoolExecutor with a fixed rate would be one way to go but I cannot get it to work due to the fact that the interval is not actually fixed.

This is for a theoretical Distributed System with high concurrency capabilities so what matters is the high scalability.

I could get away with Thread.sleep() if there was really no benefit or a viable way of doing this by writing it on my report. So does anyone have any insight on this?

It is possible to schedule tasks with ScheduledExecutorService combined with some logic. The.schedule argument lets you specify a time unit to use. You can declare a variable that can handle the increment you are trying to do.

int timer = 1000;
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    Runnable runnable = new Runnable() {
        public void run()
        {
           //Move your code you want to implement here
        }
    };
    //Increment your variable
    while(!condition()) {
        for(int i = 0; i < 5; i++) {
            service.schedule(runnable, timer, TimeUnit.SECOND);
            timer *= 2;
        }
    }

Moving your code execution within the runnable block and then scheduling it within a for loop where the timer is incremented should accomplish the effect you are going for. Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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