ScheduledExecutorService – Java program example

Posted: February 15, 2012 in Java, Technicals

An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.

Below is a Java program to schedule a service which periodically beeps every 10seconds for one hour.

import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

class BeeperControl {
private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

public static void main(String[] args){
beepForAnHour();
}

public static void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println(“beep”);
}
};
final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);

scheduler.schedule(new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
}

About these ads
Comments
  1. Sriram says:

    Please try to elaborate with some better samples. I see the same sample in oracle docs too !!!

  2. Thank You for a best sample. It was really helpful.

  3. do you know how to break this program while executing? Or is there any way to use something like scheduled tasks on windows. Set the hour and minute for launch?

  4. siva says:

    Please tell the difference between Executors.newScheduledThreadPool(1) and Executors.newSingleThreadScheduledExecutor();

  5. frfr says:

    hi, can I add this to a Tomcat and have it running while Tomcat is up?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s