Start of Tutorial > Start of Trail |
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:
public int getDelay()
delivers the preset time interval (in milliseconds)public void setDelay(int aDelay)
sets time intervalpublic void start()
starts the timerpublic void stop()
stops itjosx.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.
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
Start of Tutorial > Start of Trail |