如何在Java中设置一个定时器?

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

解决办法

因此,答案的第一部分是如何做主题所要求的事情,因为这是我最初的解释,一些人似乎觉得有帮助。 这个问题后来得到了澄清,我延长了答案以解决这个问题。

设置一个计时器

首先你需要创建一个定时器(我这里使用的是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,但任务实际上会继续运行,虽然推测数据库或网络连接最终会超时并在线程中抛出一个异常。 但要注意在这之前它可能会消耗资源。

评论(9)

使用这个

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

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

//Throw your exception
评论(10)

好吧,我想我现在明白你的问题了。 你可以用一个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
}
评论(3)