12/03/2020

[Java] Schedule tasks with ScheduledExecutorService

Java offers a ScheduledExecutorService that allows developers to create and schedule tasks.

A task is a class that implements ONE method to be executed that performs the desired duties. It is NOT necessary for the task itself to implement the Runnable interface, although the tasks will be run as a Thread.

An important thing to notice is that by default threads are NOT marked as daemons, therefore it might be worth setting such flag according to your needs.

Another important thing to note, is that the scheduler will hold on to references to cancelled tasks, which might lead to memory leaks, so it might be preferable to setRemoveOnCancelPolicy to true.

To ease one's life, it is worth then providing a custom ThreadFactory to the ScheduledExecutorService so that all generated threads are daemons:

 import java.util.concurrent.ThreadFactory;  
   
 public class DaemonThreadFactory implements ThreadFactory {  
   
  public Thread newThread(Runnable r) {  
   final Thread t = new Thread(r);  
   t.setDaemon(true);  
   
   return t;  
  }  
   
 }  


Then the scheduler can be initialized as:

 ScheduledExecutorService scheduler;  
   
 final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory());  
 executor.setRemoveOnCancelPolicy(true);  
   
 scheduler = executor;  


And out tasks can have this format:

 import java.util.concurrent.TimeUnit;  
   
 public abstract class BaseTask {  
   
  public Integer frequency;  
  public TimeUnit timeUnit;  
   
  public abstract void run();  
   
 }  


Meaning we can create any class extending our BaseTask, and pass it to the scheduler for scheduling.

Which then allows us to schedule them (for example at a provided fixed rate, starting immediately) as:

 public ScheduledFuture<?> scheduleTask(final BaseTask task) {  
   
  return scheduler.scheduleAtFixedRate(task::run, 0, task.frequency, task.timeUnit);  
   
 }  



No comments:

Post a Comment

With great power comes great responsibility