How to Set a Timer in Java
This question seeks to understand how to set a timer in Java, specifically for establishing a database connection with a timeout limit.
Setting a Timer
To create a timer, use the java.util.Timer class:
Timer timer = new Timer();
For a one-time task, schedule it with:
timer.schedule(new TimerTask() { @Override public void run() { // Your database code here } }, 2*60*1000); // 2 minutes in milliseconds
For a repeating task, schedule it with:
timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // Your database code here } }, 2*60*1000, 2*60*1000); // 2 minutes interval
Timeout for Database Connection
To implement the timeout functionality, use an ExecutorService:
ExecutorService service = Executors.newSingleThreadExecutor(); try { Runnable r = new Runnable() { @Override public void run() { // Database task } }; Future<?> f = service.submit(r); f.get(2, TimeUnit.MINUTES); // Attempt task for 2 minutes } catch (TimeoutException e) { // Task timed out } finally { service.shutdown(); }
If the database connection succeeds or fails within 2 minutes, the task will execute normally. Otherwise, a TimeoutException will be thrown. However, the task will continue running in the background, so keep that in mind.
The above is the detailed content of How to Implement a Database Connection Timeout in Java?. For more information, please follow other related articles on the PHP Chinese website!