Info
Code simply executes a single thread with fixed initial delay, and fixed interval. using two separate methods scheduleAtFixedRate and scheduleWithFixedDelay. In first run we have used scheduleAtFixedRate method, then in second run we will use the scheduleWithFixedDelay method. Inside the run method thread sleep for 6secs
Author: Raj Kirpalsinh
*/
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class SchedularTest {
private ScheduledExecutorService scheduledExecutorService ;
private WorkerThread scanner = new WorkerThread();
public static void main(String... args) {
new SchedularTest().go();
}
private void go() {
this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(scanner, scanner.getInitialDelay(), scanner.getIntervalTime(), TimeUnit.SECONDS);
//scheduledExecutorService.scheduleWithFixedDelay(scanner,scanner.getInitialDelay(), //scanner.getIntervalTime(), TimeUnit.SECONDS);
private class WorkerThread implements Runnable {
public long getInitialDelay() {
return 1;
}
public long getIntervalTime() {
return 2;
}
@Override
public void run() {
System.out.println(new Date());
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Output using scheduleWithFixedDelay
Fri Sep 26 17:00:26 IST 2014
Fri Sep 26 17:00:34 IST 2014
Fri Sep 26 17:00:42 IST 2014
Fri Sep 26 17:00:50 IST 2014
Fri Sep 26 17:00:58 IST 2014
Fri Sep 26 17:01:06 IST 2014
Fri Sep 26 17:01:14 IST 2014
Fri Sep 26 17:01:22 IST 2014
Fri Sep 26 17:01:30 IST 2014
Note : fixedDelay method consumes
Total Time =
IntervalTime + Thread Task Completion Time
check the total time between each output line you could understand it easily.
Output using scheduleAtFixedRate
Fri Sep 26 17:03:23 IST 2014
Fri Sep 26 17:03:29 IST 2014
Fri Sep 26 17:03:35 IST 2014
Fri Sep 26 17:03:41 IST 2014
Fri Sep 26 17:03:47 IST 2014
Fri Sep 26 17:03:53 IST 2014
Fri Sep 26 17:03:59 IST 2014
Note : fixedRate method consumes
Total Time =
IntervalTime
Keep Visiting :)