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:
- 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);
-
Timer and TimerTask — an older method, but less flexible.
-
Frameworks (e.g., Spring) provide
@Scheduledannotations for simplification.
It is also important to handle exceptions within the task so that the scheduler does not stop on errors.