Java ScheduledExecutorService Sample Code

Prior to Java 6, you had to create your own thread class to run a task at a regular interval. The ScheduledExecutorService Interface was introduced in Java 6 that nicely took care of this for you. You can schedule a task to run at a fixed rate or a fixed delay. What’s the difference? Good question.

The scheduleAtFixedRate() method will run at the specific interval, regardless of execution time. If you have a delay of let’s say 5 minutes, you will see your task kick off at exactly every 5 minutes.

The scheduleWithFixedDelay() method will run at the specified interval but taking into account the finish time of the previous interval. If you have a 5 minute delay configured, the next task will start at 5 minutes past the previous task finish time. Make sense?

Java ScheduledExecutorService Source Code:

package com.jcd.java.tutorials;

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


public class ScheduledExecutorServiceTutorial 
{
	
	public static void main( String[] args )
	{
		
		int initialDelay = 0;
		int executionInterval = 1;	
		ScheduledExecutorService scheduleTask = Executors.newSingleThreadScheduledExecutor();
		
		scheduleTask.scheduleAtFixedRate(new Runnable() 
		{
		
			public void run() 
			{		
				try
				{	
					System.out.println("Date="+Calendar.getInstance().getTime());
				}
				catch(Exception ex)
				{
					System.out.println("Exception:"+ex.toString());
				}
			}
		
		}, initialDelay, executionInterval, TimeUnit.MINUTES);
	
	}

}


Java ScheduledExecutorService Output

Date=Tue Jan 02 04:39:29 EST 2018
Date=Tue Jan 02 04:40:29 EST 2018
Date=Tue Jan 02 04:41:29 EST 2018
Date=Tue Jan 02 04:42:29 EST 2018
Date=Tue Jan 02 04:43:29 EST 2018



Java References:

  1. Java Executors Class
  2. Java ScheduledExecutorService Interface
  3. Java Custom Thread Pool Name Sample Code
  4. Java Thread Pool Sample Code

Add a Comment

Your email address will not be published. Required fields are marked *