Sheduledexecutorservice

public interface ScheduledExecutorService extends ExecutorService

An ExecutorService that can schedule commands to run after a given delay, or to execute periodically. [1]
It is very handy for scheduling tasks that run periodically, which is especially useful for cleanup jobs.

The following examples beeps every 5 seconds.

import static java.util.concurrent.TimeUnit.*;
import java.util.concurrent.*;
 
class MyScheduledExecutorService
{
    private final ScheduledExecutorService scheduler = Executors
            .newScheduledThreadPool(1);
 
    public void beepForAnHour()
    {
        final Runnable beeper = new Runnable()
        {
            public void run()
            {
                System.out.println("beep");
            }
        };
        final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(
                beeper, 1, 5, SECONDS);
 
         scheduler.schedule(new Runnable() {
         public void run() { beeperHandle.cancel(true); }
         }, 60 * 60, SECONDS);
    }
 
    public static void main(String args[])
    {
        MyScheduledExecutorService mses = new MyScheduledExecutorService();
        mses.beepForAnHour();
    }
}
Bibliography
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.