How to set a Timer in Java?(如何在 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.
这篇关于如何在 Java 中设置定时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中设置定时器?
				
        
 
            
        - 获取数字的最后一位 2022-01-01
 - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 - 如何指定 CORS 的响应标头? 2022-01-01
 - 未找到/usr/local/lib 中的库 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - Eclipse 的最佳 XML 编辑器 2022-01-01
 - 转换 ldap 日期 2022-01-01
 
						
						
						
						
						
				
				
				
				