A great way to implement a Java timer for your database connection is by using ScheduledExecutorService, which allows you to run tasks at fixed intervals while keeping track of elapsed time.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.*;
public class DatabaseConnector {
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
long startTime = System.currentTimeMillis();
Runnable task = () -> {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
System.out.println("Connected successfully!");
scheduler.shutdown();
} catch (SQLException e) {
if (System.currentTimeMillis() - startTime > 120_000) { // 2-minute limit
scheduler.shutdown();
throw new RuntimeException("Failed to connect within 2 minutes.", e);
}
System.out.println("Retrying...");
}
};
scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS); // Retry every 5 seconds
}
}
Why use this?
- Precise timing using scheduled retries.
- Non-blocking, allowing the program to continue running.
- Exception thrown properly after 2 minutes.
When to avoid?
If your database connection should block until success or timeout.