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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Use this
How to stop the timer? Stop and play again when do something in this code
When I use the
timer.cancel();
it will stop but if close the form and open it again the exception is thrown
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.:
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):..
To run the task once you would do:
To have the task repeat after the duration you would do:
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:
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.