如何在Java中设置Timer? [英] How to set a Timer in Java?

查看:101
本文介绍了如何在Java中设置Timer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果连接有任何问题,如何设置一个定时器(例如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();

要执行任务,请执行以下任务:

To run the task once you would do:

timer.schedule(new TimerTask() {
  @Override
  public void run() {
    // 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);

执行任务超时

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

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.

这篇关于如何在Java中设置Timer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆