问题

如果连接有任何问题,如何设置一个定时器,比如2分钟,尝试连接数据库然后抛出异常?

#1 热门回答(236 赞)

所以答案的第一部分是如何做主题所要求的内容,因为这是我最初的解释方式,而且有些人似乎觉得有帮助。问题是澄清了,我已经扩展了解决这个问题的答案。

设置计时器

首先你需要创建一个Timer(我在这里使用java.utilversion):

import java.util.Timer;

..

Timer timer = new Timer();

要执行以下任务,请执行以下操作:

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

要在持续时间之后重复执行任务:

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

使任务超时

要专门执行澄清问题所要求的,即尝试在给定时间段内执行任务,你可以执行以下操作:

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();
}

如果任务在2分钟内完成,这将在异常情况下正常执行。如果它运行的时间超过了那个,则抛出TimeoutException。

一个问题是虽然你会在两分钟后得到一个TimeoutException,但该任务实际上会继续运行,尽管可能是数据库或网络连接最终会超时并在线程中抛出异常。但请注意,在此情况发生之前,它可能会消耗资源

#2 热门回答(21 赞)

用这个

long startTime = System.currentTimeMillis();
long elapsedTime = 0L.
while (elapsedTime < 2*60*1000) {
//perform db poll/check
elapsedTime = (new Date()).getTime() - startTime;
}
//Throw your exception

#3 热门回答(9 赞)

好的,我想我现在明白你的问题。你可以使用Future尝试执行某些操作,然后在发生任何事情后稍微超时。

例如。:

FutureTask task = new FutureTask(new Callable() {
@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
}