Running a task in an executor periodically

The Executor framework provides the ThreadPoolExecutor class to execute concurrent tasks using a pool of threads that helps you avoid all thread creation operations. When you send a task to the executor, it executes the task as soon as possible according to its configuration. When it ends, the task is deleted from the executor, and if you want to execute it again, you have to send it to the executor again.

However, the Executor framework provides the possibility of executing periodic tasks through the ScheduledThreadPoolExecutor class. In this recipe, you will learn how to use this functionality of the class to schedule a periodic task.

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.