如何在Java中设置定时器?如何设置一个定时器,例如2分钟,尝试连接到数据库,然后在连接中出现任何问题时抛出异常?
3 回答

桃花长相依
TA贡献1860条经验 获得超8个赞
long startTime = System.currentTimeMillis();long elapsedTime = 0L.while (elapsedTime < 2*60*1000) { //perform db poll/check elapsedTime = (new Date()).getTime() - startTime;}//Throw your exception

白板的微信
TA贡献1883条经验 获得超3个赞
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}
添加回答
举报
0/150
提交
取消