如何在 Java 中设置计时器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4044726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set a Timer in Java?
提问by Ankita
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 分钟,以尝试连接到数据库,然后在连接出现任何问题时抛出异常?
采纳答案by andrewmu
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);
// 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);
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,但该任务实际上会继续运行,尽管可能数据库或网络连接最终会超时并在线程中引发异常。但请注意,在发生这种情况之前,它可能会消耗资源。
回答by andrewmu
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.
好的,我想我现在明白你的问题了。您可以使用 Future 尝试做某事,然后在没有发生任何事情的情况下超时。
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
}
回答by nimWM
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
回答by Mahadev Mane
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);
回答by Abhishek Garg
[Android] if someone looking to implement timer on android using java.
[Android] 如果有人希望使用 java 在 android上实现计时器。
you need use UI threadlike this to perform operations.
您需要使用这样的UI 线程来执行操作。
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
ActivityName.this.runOnUiThread(new Runnable(){
@Override
public void run() {
// do something
}
});
}
}, 2000));