next up previous
Next: 11.3 scheduleメソッド Up: 11 Timer, TimerTaskクラス Previous: 11.1 一回きりの実行

11.2 周期実行

次の例では,numWarningBeeps回だけ ``Beep''を表示してビープ音を発生させる rumメソッドをもった RemindTaskがTimertaskのサブクラスとなる. RemindTaskを作って,最初の開始時刻と, その後の周期時間をTimerのscheduleメソッドで指定する.

// AnnoyingBeep.java
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;

/**
 * Schedule a task that executes once every second.
 */

public class AnnoyingBeep {
    Toolkit toolkit;
    Timer timer;

    public AnnoyingBeep() {
        toolkit = Toolkit.getDefaultToolkit();
        timer = new Timer();
        timer.schedule(new RemindTask(),
                       0,        //initial delay
                       1*1000);  //subsequent rate
    }

    class RemindTask extends TimerTask {
        int numWarningBeeps = 3;

        public void run() {
            if (numWarningBeeps > 0) {
                toolkit.beep();
                System.out.println("Beep!");
                numWarningBeeps--;
            } else {
                toolkit.beep(); 
                System.out.println("Time's up!");
        //Not necessary because we call System.exit
                //timer.cancel(); 
        //Stops the AWT thread (and everything else)
                System.exit(0);

            }
        }
    }

    public static void main(String args[]) {
        System.out.println("About to schedule task.");
        new AnnoyingBeep();
        System.out.println("Task scheduled.");
    }
}
実行画面では,次のような形になります.
Task scheduled.
Beep!      
Beep!      //one second after the first beep
Beep!      //one second after the second beep
Time's up! //one second after the third beep


generated through LaTeX2HTML. M.Inaba 平成18年5月7日