172

How to set a Timer, say for 2 minutes, to try to connect to a Database then throw exception if there is any issue in connection?

1
  • 1
    Coul the OP clarify if they desire to simple attempt the action for at least 2 minutes, or if the exception must be thrown now later the two minutes, even if an attempt to connect is currently under way
    – thecoshman
    Jan 15, 2013 at 7:21

5 Answers 5

309

So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.

Setting a timer

First you need to create a Timer (I'm using the java.util version here):

import java.util.Timer;

..

Timer timer = new Timer();

To run the task once you would do:

timer.schedule(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* 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);

// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);

Making a task timeout

To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:

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 the task for two minutes
}
catch (final InterruptedException e) {
    // The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
    // Took too long!
}
catch (final ExecutionException e) {
    // An exception from within the Runnable task
}
finally {
    service.shutdown();
}

This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.

One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.

11
  • 8
    READERS BEWARE: This answer is blatantly wrong. It sets a timer to wait 2 minutes, and then run a DB query after that 2 minute delay, and then it runs it again and again every 2 minutes. What it does NOT do is to run the DB query right away, and then fail out after 2 minutes which is what I think the question asked for (as clarified in the comment).
    – AgilePro
    Feb 14, 2013 at 7:23
  • 2
    @AgilePro That was true. I didn't answer the question as it was eventually stated and I've now updated it to address that.
    – andrewmu
    Feb 23, 2013 at 20:29
  • 1
    @ErnestasGruodis The core APIs list the constructor as public: docs.oracle.com/javase/7/docs/api/java/util/Timer.html#Timer() You might have a different Timer class in your classpath - try java.util.Timer as the class.
    – andrewmu
    Sep 2, 2013 at 16:50
  • 4
    How you use timer.schedule() with lambda expression (since java 8)? TimerTask(first parameter) isn't even functional interface. TimerTask just an abstract class. May 26, 2020 at 12:55
  • 3
    TimerTask is not a functional interface! stackoverflow.com/questions/37970682/… Sep 11, 2020 at 7:44
27

Use this

long startTime = System.currentTimeMillis();
long elapsedTime = 0L.

while (elapsedTime < 2*60*1000) {
    //perform db poll/check
    elapsedTime = (new Date()).getTime() - startTime;
}

//Throw your exception
11
  • 1
    hmm... this would technically work, except it does not cover edge cases, where you the time runs out AS you are performing a DB poll, which may be required by the OP
    – thecoshman
    Oct 11, 2012 at 10:06
  • 1
    This is the only correct answer. It will run on a single thread, and will calculate the end time without drift. Using a TimerTask is exactly the wrong thing to do in this case. I a surprised at how many examples on StackOverflow suggest this same sort of wrong headed thing.
    – AgilePro
    Jan 14, 2013 at 18:22
  • 1
    @thecoshman - the timer implementations do NOT interrupt the DB operation once it is in progress, nor does this. In any case, you can only control the time that you start the DB operation. There is a common misconception that you need a "timer" in order to time things, but you don't. You need only to DO something, and by using the current time make sure you don't DO IT too long.
    – AgilePro
    Jan 14, 2013 at 18:35
  • let's say you have to either return the connection or throw after EXACTLY two minutes, this will not work. it will if AFTER two minutes of trying to connect you have still failed to connect. In a situation where the connection check takes say two weeks, this will take that long to throw an exception.
    – thecoshman
    Jan 14, 2013 at 23:47
  • 20
    This is actually very bad coding style, since the while loop constantly runs and checks for stuff... bad for the cpu and bad for the battery life time.
    – Infinite
    Jul 2, 2013 at 18:49
12

Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit if 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
}
3
  • Exception is thrown but the program is not getting terminated.Please help me through this.
    – Ankita
    Nov 2, 2010 at 13:22
  • 2
    You can use ExecutorService class instead of Executor. It has shutdown() method to stop the executor.
    – Rites
    Nov 2, 2010 at 13:35
  • 1
    Executors will swallow thrown exceptions that you don't specifically handle in your Callable/Runnable. If your Runnable/Callable doesn't catch and handle the exception itself and it is provided to you vs you owning it, then you need to subclass the ScheduledExecutorService and override afterExecute (make sure to call super.afterExecute()). The second argument to afterExecute will be the throwable from the Runnable/Callable
    – adam
    Mar 28, 2012 at 21:30
4
    new java.util.Timer().schedule(new TimerTask(){
        @Override
        public void run() {
            System.out.println("Executed...");
           //your code here 
           //1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly 
        }
    },1000*5,1000*5); 
2
4

[Android] if someone looking to implement timer on android using java.

you need use UI thread like this to perform operations.

Timer timer = new Timer();
timer.schedule(new TimerTask() {
           @Override
            public void run() {
                ActivityName.this.runOnUiThread(new Runnable(){
                    @Override
                      public void run() {
                       // do something
                      }        
                });
            }
        }, 2000));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.