Using Executors in Java to run code repeatedly at given intervals

Home / java / Using Executors in Java to run code repeatedly at given intervals
Published on July 24, 2026
Updated on August 3, 2026
3 min read

problem

You wish to run a piece of code in your Java application repeatedly on a given interval, for example every 10 minutes. In this post we will see how to achieve this by using ExecutorService provided by Java.

SOLUTION

Java offers Executor and ExecutorService classes for achieving this from the java.util.concurrent package. Moreover, we want a Task class to be executed repeatedly by the executor service. Below we will make a Timer app that will print the current time every second.

Runner.java
				
					ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

long delay = 0; //delay to start execution
long period = 1; //periodic interval, i.e. 1 second

TimeUnit timeUnit = TimeUnit.SECONDS;

PrintTimeTask printTimeTask = new PrintTimeTask(); 

ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(printTimeTask, delay, period, timeUnit);

				
			
PrintTimeTask.java
				
					import java.time.LocalTime;

public class PrintTimeTask implements Runnable {

   @Override
   public void run() {
       System.out.println(LocalTime.now());
   }
}
				
			

Let’s put the code in a Runner class with a main method so it can be executed. The complete code:

Runner.java
				
					import java.util.concurrent.*;

public class Runner {

   static void main() {

       ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

       long delay = 5; //initial delay to start execution. i.e. wait for 5 seconds
       long period = 1; //periodic interval, i.e. repeat every 1 second
       
       TimeUnit timeUnit = TimeUnit.SECONDS;

       System.out.println("Starting in 5 seconds");

       PrintTimeTask printTimeTask = new PrintTimeTask();
       
       ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(printTimeTask, delay, period, timeUnit);
   }
}

				
			

In the code, I added an initial delay of 5 seconds. The program executes and 5 seconds later, the executor service will invoke the run() method. Then, repeat every second.

running

I executed it via IntelliJ

Run Runner.java to repeatedly execute code
output
Printing time every second in Java

It periodically executes the run() method in the PrintTimeTask object. It does not stop executing in this case.

Create a new Task to stop it

In order to stop the executor service from our program, we need to shut it down. Also, the scheduledFuture needs to be cancelled. 

To do this, let’s create a StopTimerTask< class with the same approach to PrintTimeTask, implementing Runnable. This task will accept 2 objects as constructor parameters: the executorService and scheduledFuture.
PrintTimeTask.java
				
					import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledFuture;

public class StopTimerTask implements Runnable {

   private final ExecutorService executorService;
   private final ScheduledFuture<?> scheduledFuture;

   public StopTimerTask(ExecutorService executorService, ScheduledFuture<?> scheduledFuture) {
       this.executorService = executorService;
       this.scheduledFuture = scheduledFuture;
   }

   @Override
   public void run() {
       System.out.println("Stopping timer task and service!");
       scheduledFuture.cancel(true);
       executorService.shutdown();
   }
}

				
			
Did you know?

In this case, passing the 2 parameters in the constructor, it's called dependency injection (via constructor).

Then, we initialize them to class fields and have them available in the run() method in which we will invoke the cancel and shutdown methods on the objects respectively.

Then expect it will stop gracefully executing the PrintTimeTask and exit the program.

Schedule a new Task with delay

Now, let’s schedule this new task using the predefined scheduler service. This time, we will use the schedule() method and not the scheduleAtFixedRate() method. This will start the StopTimerTask after an initial delay and it will not repeat. I set the delay to 7 seconds, meaning, the PrintTimerTask will be stopped after 7 seconds by the StopTimerTask.

Runner.java
				
					long delayToStop = 7;
System.out.println("Stopping after 7 seconds");
scheduledExecutorService.schedule(new StopTimerTask(scheduledExecutorService, scheduledFuture), delayToStop, timeUnit);

				
			
running

Recompile and Re – run it in IntelliJ

The complete Runner class code

Runner.java
				
					import java.util.concurrent.*;

public class Runner {

   static void main() {

       ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

       long delay = 0; //no initial delay
       long period = 1; //periodic interval, i.e. repeat every 1 second
       TimeUnit timeUnit = TimeUnit.SECONDS;

       System.out.println("Starting..");

       PrintTimeTask printTimeTask = new PrintTimeTask();
       ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(printTimeTask, delay, period, timeUnit);

       long delayToStop = 7;
       System.out.println("Stopping after 7 seconds");
       scheduledExecutorService.schedule(new StopTimerTask(scheduledExecutorService, scheduledFuture), delayToStop, timeUnit);
   }
}
				
			
Small change: I removed the initial delay for PrintTimeTask for this example so it starts immediately printing the local time and stops after 7 seconds. If the initial delay was left at 5 seconds, then it would only print the time for 2 seconds.
output
Stopping ExecutorService after given seconds

Correct . We can see the process finishes with exit code 0 as expected!

conclusion

In this post we saw how to use the Executors and in particular the ScheduledExecutorService. Methods used:

  • To run periodically: scheduleAtFixedRate()
  • To run once: schedule()

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies (Ads)

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings. We use Google Ads on this site.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.