1 saat boyunca 10 saniyede bir ekrana merhaba yazacak bir örnek ScheduledExecutorService kullanılarak yapılabilir. Aşağıdaki örnek bu işlevi yerine getirmektedir:
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
public class Greeting {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void forAnHour() {
final Runnable greeter = new Runnable() {
public void run() {
System.out.println("merhaba");
}
};
//10 snde bir merhaba yazacak
final ScheduledFuture<?> greeterHandle =
scheduler.scheduleAtFixedRate(greeter, 10, 10, SECONDS);
// bir saat sonra sona erdirilecek
scheduler.schedule(new Runnable() {
public void run() {
greeterHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
public static void main(String[] args) {
Greeting greeting=new Greeting();
greeting.forAnHour();
}
}
Öncelikle greeter adında erkana merhaba yazan bir Runnable yaratıyoruz. scheduleAtFixedRate ile 10 sn'de bir bu Runnable çalıştırılacak şekilde ayarlanmıştır. schedule() yöntemi ile de 1 saat sonra bir task çalışacak ve 10 sn bir çalışan greeterHandle durdurulacaktır.
Uygulama çalıştığında 10 sn'de bir merhaba yazısı çıktıda görülecektir:
merhaba
merhaba
merhaba
merhaba
merhaba
merhaba