adam bien's blog

ScheduledExecutorService--A TimerTask Alternative 📎

TimerTask, introduced with Java 1.3, can be used to schedule periodic tasks:

import java.util.Timer;
import java.util.TimerTask;
    
@Test
public void timerTask() {
    Timer timer = new Timer("dots",false);
    TimerTask task = new TimerTask(){
        @Override
        public void run() {
            System.out.println("|");				
        }
        
    };
    timer.scheduleAtFixedRate(task, 0, 2000);
    
}    

The ScheduledExecutorService, introduced with Java 1.5, is a convenient alternative to TimerTask:


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
    
@Test
public void singleThreadScheduledExecutorVerbose() {
    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    Runnable task = () -> System.out.println(".");
    ses.scheduleAtFixedRate(task, 0, 2, TimeUnit.SECONDS);
}    

The managed, "enterprise" version: ManagedScheduledExecutorService could be also used as an alternative to EJB Timers.