Execute a process at regular intervalTag(s): Thread


JDK1.3 introduces a way to execute a process at regular interval (java.util.Timer and java.util.TimerTask).

JDK1.5 provides a mechanism to create a pool a scheduled task (java.util.concurrent.ScheduledThreadPoolExecutor (javadoc)).

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class DemoScheduledTask {

  public static void main(String args[]) {

      // pool size == 5
      ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(5);
      SimpleTask01 st01 = new SimpleTask01();
      // start right now and after every 5 sec.
      stpe.scheduleAtFixedRate(st01, 0, 5, TimeUnit.SECONDS);

      SimpleTask02 st02 = new SimpleTask02();
      // start in 1 sec and after every 2 sec.
      stpe.scheduleAtFixedRate(st02, 1, 2, TimeUnit.SECONDS);
  }
}

class SimpleTask01 implements Runnable {
    public void run() {
        System.out.println("Real's HowTo");
    }
}

class SimpleTask02 implements Runnable {
    int current = 10;
    public void run() {
        if (current > 0) {
            System.out.println(current--);
            if (current == 0) {
                System.out.println("end.");
            }
        }
    }
}

blog comments powered by Disqus