如何在Java中设置定时器?

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

所以答案的第一部分是如何做主题提出的问题,因为这是我最初的解释,有些人似乎find了帮助。 问题是因为澄清,我已经扩大了解决这个问题的答案。

设置一个计时器

首先你需要创build一个Timer(我在这里使用java.util版本):

 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。

一个问题是,尽pipe在两分钟后你会得到一个TimeoutException,但是实际上这个任务仍然会继续运行 ,尽pipe大概数据库或者networking连接最终会超时并且在线程中抛出一个exception。 但要注意,在这种情况发生之前它可能会消耗资源

用这个

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

好吧,我想我现在明白你的问题了。 您可以使用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 } 

如何停止计时器? 在这段代码中做些事情时停下来再玩一遍

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

当我使用timer.cancel();

它将停止,但如果closures表单并再次打开,将引发exception

 Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Timer already cancelled. at java.util.Timer.sched(Timer.java:354) at java.util.Timer.scheduleAtFixedRate(Timer.java:296) at View.Electronic_Meeting.this_componentShown(Electronic_Meeting.java:295) at View.Electronic_Meeting.access$000(Electronic_Meeting.java:36) at View.Electronic_Meeting$1.componentShown(Electronic_Meeting.java:85) at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162) at java.awt.Component.processComponentEvent(Component.java:6095) at java.awt.Component.processEvent(Component.java:6043) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4630) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) 
  new java.util.Timer().schedule(new TimerTask(){ @Override public void run() { System.out.println("Executed..."); //your code here //1000*5=5000 mlsec. ie 5 seconds. u can change accordngly } },1000*5,1000*5);