如何在Java中设置Timer?

时间:2010-10-28 15:59:07

标签: java timer

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

6 个答案:

答案 0 :(得分:257)

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

设置计时器

首先你需要创建一个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);
// Since Java-8
timer.schedule(() -> /* 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);

// Since Java-8
timer.scheduleAtFixedRate(() -> /* 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,该任务实际上将继续运行,尽管可能是数据库或网络连接最终会超时并抛出异常线程。但请注意,在发生这种情况之前,它可能会消耗资源。

答案 1 :(得分:23)

使用此

long startTime = System.currentTimeMillis();
long elapsedTime = 0L.

while (elapsedTime < 2*60*1000) {
    //perform db poll/check
    elapsedTime = (new Date()).getTime() - startTime;
}

//Throw your exception

答案 2 :(得分:9)

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

E.g:

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
}

答案 3 :(得分:7)

如何停止计时器?在此代码中执行某些操作时停止并再次播放

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

当我使用timer.cancel();

它会停止但是如果关闭表单并再次打开则抛出异常

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)

答案 4 :(得分:2)

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

答案 5 :(得分:1)

[Android](如果有人希望使用Java在Android上实现 timer )。

  

您需要像这样使用 UI线程来执行操作。

Timer timer = new Timer();
timer.schedule(new TimerTask() {
           @Override
            public void run() {
                ActivityName.this.runOnUiThread(new Runnable(){
                    @Override
                      public void run() {
                       // do something
                      }        
                });
            }
        }, 2000));