如何在 Java 中设置定时器?

2022-01-30 00:00:00 timer java

如何设置一个计时器,比如 2 分钟,尝试连接到数据库,如果连接有任何问题,则抛出异常?

How to set a Timer, say for 2 minutes, to try to connect to a Database then throw exception if there is any issue in connection?

推荐答案

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

So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.

设置计时器

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

First you need to create a Timer (I'm using the java.util version here):

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

让任务在你将做的持续时间后重复:

To have the task repeat after the duration you would do:

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

使任务超时

要具体执行澄清问题所要求的内容,即尝试在给定时间段内执行任务,您可以执行以下操作:

To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:

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.

This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.

一个问题是,尽管两分钟后您会收到 TimeoutException,但任务实际上会继续运行,尽管可能数据库或网络连接最终会超时并在线程.但请注意,在这种情况发生之前它可能会消耗资源.

One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.

相关文章