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.

Scenario

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

Implementation

Let’s see the code for this

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 *