Java 循环每分钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2702980/
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
Java Loop every minute
提问by Robert Cardona
I want to write a loop in Java that firs starts up and goes like this:
我想用 Java 编写一个循环,它首先启动并像这样:
while (!x){
//wait one minute or two
//execute code
}
I want to do this so that it does not use up system resources. What is actually going on in the code is that it goes to a website and checks to see if something is done, if it is not done, it should wait another minute until it checks again, and when its done it just moves on. Is their anyway to do this in java?
我想这样做,这样它就不会耗尽系统资源。代码中实际发生的事情是,它访问网站并检查是否完成了某些操作,如果未完成,则应再等待一分钟,直到再次检查,完成后它就继续前进。他们无论如何要在java中做到这一点吗?
采纳答案by polygenelubricants
Use Thread.sleep(long millis)
.
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
使当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,取决于系统计时器和调度程序的精度和准确性。该线程不会失去任何监视器的所有权。
One minute would be (60*1000) = 60000
milliseconds.
一分钟就是(60*1000) = 60000
几毫秒。
For example, this loop will print the current time once every 5 seconds:
例如,此循环将每 5 秒打印一次当前时间:
try {
while (true) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
If your sleep period becomes too large for int
, explicitly compute in long
(e.g. 1000L
).
如果您的睡眠时间对于 来说太大int
,则在long
(例如1000L
)中明确计算。
回答by Chuk Lee
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();
回答by OscarRyz
回答by Basil Bourque
ScheduledExecutorService
ScheduledExecutorService
The Answer by Leeis close, but only runs once. The Question seems to be asking to run indefinitely until an external state changes (until the response from a web site/service changes).
李的答案很接近,但只运行一次。问题似乎要求无限期运行,直到外部状态发生变化(直到来自网站/服务的响应发生变化)。
The ScheduledExecutorService
interface is part of the java.util.concurrent
package built into Java 5 and later as a more modern replacement for the old Timer
class.
该ScheduledExecutorService
接口是java.util.concurrent
内置于 Java 5 和更高版本中的包的一部分,作为旧Timer
类的更现代替代品。
Here is a complete example. Call either scheduleAtFixedRate
or scheduleWithFixedDelay
.
这是一个完整的例子。调用scheduleAtFixedRate
或scheduleWithFixedDelay
。
ScheduledExecutorService executor = Executors.newScheduledThreadPool ( 1 );
Runnable r = new Runnable () {
@Override
public void run () {
try { // Always wrap your Runnable with a try-catch as any uncaught Exception causes the ScheduledExecutorService to silently terminate.
System.out.println ( "Now: " + Instant.now () ); // Our task at hand in this example: Capturing the current moment in UTC.
if ( Boolean.FALSE ) { // Add your Boolean test here to see if the external task is fonud to be completed, as described in this Question.
executor.shutdown (); // 'shutdown' politely asks ScheduledExecutorService to terminate after previously submitted tasks are executed.
}
} catch ( Exception e ) {
System.out.println ( "Oops, uncaught Exception surfaced at Runnable in ScheduledExecutorService." );
}
}
};
try {
executor.scheduleAtFixedRate ( r , 0L , 5L , TimeUnit.SECONDS ); // ( runnable , initialDelay , period , TimeUnit )
Thread.sleep ( TimeUnit.MINUTES.toMillis ( 1L ) ); // Let things run a minute to witness the background thread working.
} catch ( InterruptedException ex ) {
Logger.getLogger ( App.class.getName () ).log ( Level.SEVERE , null , ex );
} finally {
System.out.println ( "ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed." );
executor.shutdown ();
}
Expect output like this:
期待这样的输出:
Now: 2016-12-27T02:52:14.951Z
Now: 2016-12-27T02:52:19.955Z
Now: 2016-12-27T02:52:24.951Z
Now: 2016-12-27T02:52:29.951Z
Now: 2016-12-27T02:52:34.953Z
Now: 2016-12-27T02:52:39.952Z
Now: 2016-12-27T02:52:44.951Z
Now: 2016-12-27T02:52:49.953Z
Now: 2016-12-27T02:52:54.953Z
Now: 2016-12-27T02:52:59.951Z
Now: 2016-12-27T02:53:04.952Z
Now: 2016-12-27T02:53:09.951Z
ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed.
Now: 2016-12-27T02:53:14.951Z