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?
如何设置一个计时器,比如2分钟,尝试连接到数据库,如果连接中有任何问题,抛出异常?
5 个解决方案
#1
230
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.
所以答案的第一部分是如何做题目问的,因为这是我最初的解释,一些人似乎觉得很有帮助。这个问题后来被澄清了,我扩展了答案来解决这个问题。
Setting a timer
设置一个计时器
First you need to create a Timer (I'm using the java.util
version here):
首先需要创建一个计时器(我正在使用java)。util版本):
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);
Making a task timeout
使一个任务超时
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();
}
This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.
如果任务在2分钟内完成,此操作将正常执行。如果运行的时间超过此时间,则抛出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.
一个问题是,尽管在两分钟后您将获得一个TimeoutException,但任务实际上将继续运行,尽管数据库或网络连接最终将超时并在线程中抛出异常。但要注意,在这种情况发生之前,它可能会消耗资源。
#2
21
Use this
使用这个
long startTime = System.currentTimeMillis();
long elapsedTime = 0L.
while (elapsedTime < 2*60*1000) {
//perform db poll/check
elapsedTime = (new Date()).getTime() - startTime;
}
//Throw your exception
#3
9
Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit if nothing has happened.
好的,我想我现在明白你的问题了。你可以用未来来尝试做一些事情,如果什么事都没有发生,那么可以在一段时间后暂停。
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
}
#4
6
How to stop the timer? Stop and play again when do something in this code
如何停止计时器?当在此代码中做一些事情时,停止并再次播放
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000, 2*60*1000);
When I use the timer.cancel();
当我使用timer。cancel();
it will stop but if close the form and open it again the exception is thrown
它将停止,但如果关闭表单并再次打开它,就会抛出异常。
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)
#5
1
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);
#1
230
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.
所以答案的第一部分是如何做题目问的,因为这是我最初的解释,一些人似乎觉得很有帮助。这个问题后来被澄清了,我扩展了答案来解决这个问题。
Setting a timer
设置一个计时器
First you need to create a Timer (I'm using the java.util
version here):
首先需要创建一个计时器(我正在使用java)。util版本):
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);
Making a task timeout
使一个任务超时
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();
}
This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.
如果任务在2分钟内完成,此操作将正常执行。如果运行的时间超过此时间,则抛出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.
一个问题是,尽管在两分钟后您将获得一个TimeoutException,但任务实际上将继续运行,尽管数据库或网络连接最终将超时并在线程中抛出异常。但要注意,在这种情况发生之前,它可能会消耗资源。
#2
21
Use this
使用这个
long startTime = System.currentTimeMillis();
long elapsedTime = 0L.
while (elapsedTime < 2*60*1000) {
//perform db poll/check
elapsedTime = (new Date()).getTime() - startTime;
}
//Throw your exception
#3
9
Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit if nothing has happened.
好的,我想我现在明白你的问题了。你可以用未来来尝试做一些事情,如果什么事都没有发生,那么可以在一段时间后暂停。
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
}
#4
6
How to stop the timer? Stop and play again when do something in this code
如何停止计时器?当在此代码中做一些事情时,停止并再次播放
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000, 2*60*1000);
When I use the timer.cancel();
当我使用timer。cancel();
it will stop but if close the form and open it again the exception is thrown
它将停止,但如果关闭表单并再次打开它,就会抛出异常。
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)
#5
1
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);