Search code examples
javamultithreadingconcurrency

scheduleAtFixedRate executes task immediately, should run after defined delay.


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

class MyTask1 implements Runnable{
MyTask1(){
    new Thread(this).start();
}
public void run(){
    System.out.println("Running");
}
}
public class Schedular_1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    ScheduledExecutorService ex = Executors.newScheduledThreadPool(1);
    ex.scheduleAtFixedRate(new MyTask1(), 3, 10, TimeUnit.SECONDS); 
  }

 }

scheduleAtFixedRate 's first run is expected after delay we defined in 2nd parameter. And subsequent execution has to be defined by 3rd parameter ie every 10 seconds. But actually it(MyTask1) is running immediately as soon as I invoke main method. after 3 seconds it executes for 2nd time and after every 10 seconds it runs periodically.

I got another version of this that works fine available here (link).

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

class MyTask1 implements Runnable{
MyTask1(){
    new Thread(this).start();
}
public void run(){
    System.out.println("Running");
}
}
public class Schedular_1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    ScheduledExecutorService ex = Executors.newScheduledThreadPool(1);
    ex.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            System.out.println("Testing...");
        }
    }, 3, 10, TimeUnit.SECONDS);
}

}

What is the difference between these 2 veriations. Why it behaves abnormally?


Solution

  • You don't need start Thread in your MyTask1. The correct version of MyTask1 is going to be:

    class MyTask1 implements Runnable{
        MyTask1(){
        }
        public void run(){
            System.out.println("Running");
        }
    }