Scheduling tasks using Concurrency API

The last two methods in above table are similar as they both perform the same task repeatedly, after completing some initial delay. The difference is related to the timing of the process and when the next task starts. The scheduledAtFixedRate() method creates a new task and submits it to the executor every period, regardless of whether or not the previous task finished. The following example executes a Runnable task every minute, following an initial five-minute delay :

service.scheduleAtFixedRate(command, 5, 1, TimeUnit.MINUTE);

On the other hand, the scheduledAtFixedDelay() method creates a new task after the previous task has finished. The following example executes each next Runnable task 2 minutes after the previous task has finished, following no initial delay :

service.scheduleAtFixedDelay(command, 0, 2, TimeUnit.MINUTE);

Note that neither of methods, scheduleAtFixedRate() and scheduledAtFixedDelay(), take a Callable object as an input parameter. Since these tasks are scheduled to run infinitely, as long as the ScheduledExecutorService is still alive, they would generate an endless series of Future objects.

Each of the ScheduledExecutorService methods is important and has real-world applications. schedule() command can be used to check on the state of processing a task and send out notifications if it is not finished or even call schedule() again to delay processing.

scheduleAtFixedRate() is useful for tasks that need to be run at specific intervals, such as checking something once a day. Even if it takes some time to accomplish task, this doesn’t mean that next check should start any later.

scheduledAtFixedDelay() is useful for processes that have to be happened repeatedly but whose specific time is unimportant. For example, it can be hauling the goods from the stock for restocking the salad bar.

Previous

Leave a Reply

Your email address will not be published. Required fields are marked *