每分钟Java循环

Rob*_*ona 26 java time loops

我想在Java中编写一个第一个启动的循环,如下所示:

while (!x){
    //wait one minute or two

    //execute code
}
Run Code Online (Sandbox Code Playgroud)

我想这样做,以便它不会耗尽系统资源.在代码中实际发生的是它进入一个网站并检查是否已完成某些事情,如果没有完成,它应该等待一分钟直到它再次检查,并且当它完成时它只是继续.无论如何他们在java中这样做?

pol*_*nts 54

使用Thread.sleep(long millis).

导致当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性.该线程不会失去任何监视器的所有权.

一分钟就是(60*1000) = 60000几毫秒.


例如,此循环将每5秒打印一次当前时间:

    try {
        while (true) {
            System.out.println(new Date());
            Thread.sleep(5 * 1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

如果您的睡眠时间变得太大int,请在long(例如1000L)中明确计算.


Osc*_*Ryz 54

你可以使用Timer

Timer timer = new Timer();

timer.schedule( new TimerTask() {
    public void run() {
       // do your work 
    }
 }, 0, 60*1000);
Run Code Online (Sandbox Code Playgroud)

什么时候到来

  timer.cancel();
Run Code Online (Sandbox Code Playgroud)

关闭它.

  • @poly:它会像OP一样等待一分钟.[Timer#scheduleAtFixedRate()](http://java.sun.com/javase/6/docs/api/java/util/Timer.html#scheduleAtFixedRate%28java.util.TimerTask,%20long,%20long%29做你说的. (4认同)
  • @BalusC:啊,有意思!`schedule`在执行之间以固定的延迟运行,并且`scheduleAtFixedRate`以固定的间隔运行.太好了! (3认同)

Chu*_*Lee 13

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();
Run Code Online (Sandbox Code Playgroud)

  • 如果你只需要一个线程,你可以使用 `Executors.newSingleThreadScheduledExecutor()` 而不是 `Executors.newScheduledThreadPool(1);` (3认同)

Bas*_*que 6

ScheduledExecutorService

答案很接近,但只运行一次.该问题似乎要求无限期运行,直到外部状态发生变化(直到网站/服务的响应发生变化).

ScheduledExecutorService接口是java.util.concurrentJava 5中内置的包的一部分,后来作为旧Timer类的更现代的替代品.

这是一个完整的例子.打电话给scheduleAtFixedRatescheduleWithFixedDelay.

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 ();
}
Run Code Online (Sandbox Code Playgroud)

期待这样的输出:

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
Run Code Online (Sandbox Code Playgroud)