簡體   English   中英

Java 循環每分鍾

[英]Java Loop every minute

我想用 Java 編寫一個循環,它首先啟動並像這樣:

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

    //execute code
}

我想這樣做,這樣它就不會耗盡系統資源。 代碼中實際發生的事情是,它訪問網站並檢查是否完成了某些操作,如果未完成,則應再等待一分鍾,直到再次檢查,完成后它就繼續前進。 他們無論如何要在java中做到這一點嗎?

您可以使用定時器

Timer timer = new Timer();

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

當時代到來

  timer.cancel();

要關閉它。

使用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();
    }

如果您的睡眠時間對於int來說太大,請明確計算long (例如1000L )。

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

ScheduledExecutorService

答案很接近,但只運行一次。 問題似乎要求無限期運行,直到外部狀態發生變化(直到來自網站/服務的響應發生變化)。

ScheduledExecutorService接口是 Java 5 及更高版本java.util.concurrent內置的java.util.concurrent包的一部分,作為舊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 ();
}

期待這樣的輸出:

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

如果您使用的是 SpringBoot 應用程序,它就像

預定進程

@Log
@Component
public class ScheduledProcess {

    @Scheduled(fixedRate = 5000)
    public void run() {
        log.info("this runs every 5 seconds..");
    }

}

應用程序類

@SpringBootApplication
// ADD THIS ANNOTATION TO YOUR APPLICATION CLASS
@EnableScheduling
public class SchedulingTasksApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulingTasksApplication.class);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM