tags:

views:

44

answers:

2

How to set a Timer say for 2 minutes to try to connect to a database and then exception out if there is any issue in connecting

+1  A: 

First you need to create a Timer:

Timer timer = new Timer();

To run the task once would would do:

timer.schedule(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000);

To have the task repeat after the duration you would do:

timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000, 2*60*1000);
andrewmu
Oh I guess you got my problem wrong, I have to repeatedly try to to connect to database till 2 minutes everytime
Ankita
I updated my answer to cover repeating every 2 minutes
andrewmu
I am sorry but my requirement is that I want to give 2 minutes to connect to the database and then it will just throw some error message.It is like I want to set a time limit to try to connect to the database
Ankita
+1  A: 

Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit of nothing has happened.

E.g.:

FutureTask<Void> task = new FutureTask<Void>(new Callable<Void>() {
  @Override
  public Void call() throws Exception {
    // Do DB stuff
    return null;
  }
});

Executor executor = Executors.newSingleThreadScheduledExecutor();
executor.execute(task);

try {
  task.get(5, TimeUnit.SECONDS);
}
catch(Exception ex) {
  // Handle your exception
}
andrewmu