簡體   English   中英

ScheduledExecutorService 將執行與之前的任務完成狀態無關

[英]ScheduledExecutorService will execute irrespective of previous task completion status

我正在使用ScheduledExecutorService ,有時任務可能會運行 3 小時才能完成pollMergeFiles.searchForFileAndExecute()方法,有時可能需要不到 2 分鍾才能完成。

我唯一的問題是scheduler.scheduleAtFixedRate是否會每 10 分鍾執行一次,延遲 5 分鍾,還是會等到上一個任務運行完成,然后才開始新任務?

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    ...
    PollMergeFiles pollMergeFiles = new PollMergeFiles();
    final Runnable service = new Runnable() {
        public void run() {
            try {
                if (counter <= 256) {
                    pollMergeFiles.searchForFileAndExecute();
                } else if (counter > 256) {
                    logger.info(
                            "Shutdown the scheduler service since all counters were processed");
                    scheduler.shutdown();
                }
            } catch (Exception e) {
                logger.error("Exception found", e);
            }
        }
    };

    scheduler.scheduleAtFixedRate(service, 5, 10, TimeUnit.Minutes);

您可以查看 Java 文檔https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 創建並執行一個周期性動作,在給定的初始延遲后首先啟用,然后在給定的時間段內啟用; 即執行將在 initialDelay 之后開始,然后是 initialDelay+period,然后是 initialDelay + 2 * period,依此類推。

所以 scheduleAtFixedRate() 不會等待最后一個任務完成。 它將以預定義的時間間隔(周期字段)執行。

scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) 創建並執行一個周期性動作,該動作首先在給定的初始延遲后啟用,隨后在一個執行終止和下一個執行開始之間具有給定的延遲。

但是 scheduleWithFixedDelay() 方法可以在最后一個任務執行后等待一個預定義的時間(延遲字段)。

暫無
暫無

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

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