如何设置计时器,比如2分钟,以尝试连接到数据库,然后在连接出现任何问题时抛出异常?
发布于 2012-07-17 23:35:02
使用这个
long startTime = System.currentTimeMillis();
long elapsedTime = 0L.
while (elapsedTime < 2*60*1000) {
//perform db poll/check
elapsedTime = (new Date()).getTime() - startTime;
}
//Throw your exception
发布于 2010-10-30 01:14:16
好了,我想我现在明白你的问题了。您可以使用Future尝试做一些事情,然后在没有发生任何事情的情况下超时一段时间。
例如:
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
}
发布于 2017-05-06 21:13:40
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);
https://stackoverflow.com/questions/4044726
复制相似问题