Tuesday, October 11, 2011

How to Schedule Recurring Tasks in Java

Prior to Java 5, to schedule recurring tasks, we need to use java.util.Timer and java.util.TimerTask.
import java.util.Timer;
import java.util.TimerTask;

public class WithTimerTask {
    
    public static void main(String[] args) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Do something");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 0, 1000);
    }
}
From Java 5 onwards, we can easily replace java.util.Timer and java.util.TimerTask with java.util.concurrent.ScheduledExecutorService.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class WithScheduledExecutorService {

    public static void main(String[] args) {
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
        ses.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("Do something");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, 0, 1000, TimeUnit.MILLISECONDS);
    }
}
java.util.concurrent.ScheduledExecutorService has more advantages as compared to java.util.TimerTask, such as being able to use a thread pool and not being sensitive to system clock. So whenever possible, use java.util.ScheduledExecutorService as opposed to java.util.TimerTask.

No comments:

Post a Comment