The leJOS Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail

Trail: Essential leJOS classes
Lesson: Utilities

Utilities: Timer

The Timer class is of utmost use when your robot needs to execute tasks depending on some timed event like determining every minute its position in space or sending a signal to Houston every ten seconds.

Class Timer is contained in the josx.util package and it works similar to the javax.swing.Timer class:
A TimerListener repeatedly notifies the Timer in preset time intervals.

According to this the API is pretty straightforward:

The josx.util.TimerListener is set in the constructor

            public Timer(int aDelay, TimerListener aListener) 
        
and calls its

            public void timedOut() 
        
method every time the interval is gone by.

A complete example which uses the Timer class


            import josx.platform.rcx.*;
            import josx.util.*;

            //////////////////////////////////////
            /**
            * Represents a Timer sample application.
            *
            * @author The leJOS Tutorial
            * @version 1.0 
            */
            public class TimerSample implements TimerListener {        

                ////////////////////////////////////////////
                // public methods
                ////////////////////////////////////////////

                ////////////////////////////////////////////
                /**
                 * main method 
                 * @throws InterruptedException
                 */
                public static void main(String[] args) 
                    throws InterruptedException {
                    // create & start timer
                    // delay is one second
                    Timer timer = new Timer(1000,new TimerSample());
                    timer.start();
                    // just run until RUN button is pressed again
                    Button.RUN.waitForPressAndRelease();
                    // stop timer
                    timer.stop();
                } // main()

                ////////////////////////////////////////////
                // Timerlistener methods
                ////////////////////////////////////////////

                ////////////////////////////////////////////
                /**
                * Called every time the Timer fires
                */
                public void timedOut() {
                    // just beep
                    Sound.beep();
                } // timedOut()

            } // class TimerSample
        

The Timer API

may be found here.
The leJOS Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail