How to run periodic tasks in Java

Running periodic tasks like Health checking, remote site health monitoring is a common need. In this post let’s see how to achieve it in Java.

Periodic tasks can be executed in Java using ScheduledExecutorService.


We need to monitor a remote Service or a DB and update periodically in DB.


Let’s see the code for this

package com.codezuzu;

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

public class ScheduledChecks {

  static class HealthChecker implements Runnable {

    public void run() {
      // do health Check
      System.out.println("Health check completed");
      // update in peristent Storage

  public static void main(String[] args) {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    scheduledExecutorService.schedule(new HealthChecker(), 1, TimeUnit.MINUTES);


We have created the HealthChecker class for maintaining the Health Context. It’s responsible handling actual monitoring work. In the code example, we have left the place holder for actual work done, for a DB we would create a connection and then execute a simple query periodically. For a remote Http based Service we would check for Status code as 200.

Now comes the scheduling part. ScheduledExecutorService is the class that provides functionality to periodically execute tasks. We submit out task to the service and specify the delay of execution. In the code sample, it’s 1 minute. It can be set as per Application specific needs.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.