简体   繁体   中英

ScheduledExecutorService will execute irrespective of previous task completion status

I am using ScheduledExecutorService where at times task may run for 3 hours to complete pollMergeFiles.searchForFileAndExecute() method and some times it may take less than 2 minutes to complete.

My only question is if scheduler.scheduleAtFixedRate will end up executing every 10 minutes with a delay of 5 minutes or it will wait until previous task running to be completed and only then start new task?

    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);

You can check the Java doc https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html .

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.

So scheduleAtFixedRate() won't wait for last task to finish. It will be executed at predefined interval (period field).

scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

But scheduleWithFixedDelay() method can wait for a predefined time (delay field) after the last task is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM