Sobes.tech
Junior — Middle

How to implement repeated database queries at a certain interval?

sobes.tech AI

Answer from AI

To perform recurring database queries at a certain interval in Java, you can use several approaches:

  1. ScheduledExecutorService — a built-in task scheduler in Java:
import java.util.concurrent.*;

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

Runnable task = () -> {
    // Database query logic
    System.out.println("Executing database query");
};

// Start the task with a delay of 0 and repeat every 10 seconds
scheduler.scheduleAtFixedRate(task, 0, 10, TimeUnit.SECONDS);
  1. Timer and TimerTask — an older method, but less flexible.

  2. Frameworks (e.g., Spring) provide @Scheduled annotations for simplification.

It is also important to handle exceptions within the task so that the scheduler does not stop on errors.