Search code examples
javaexecutorservicethreadpoolexecutorthread-sleepscheduledexecutorservice

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 (e.g. 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?


Solution

  • 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!