Table of ContentsThe MIDlet ApplicationNetworking

Using Timers

The MIDP API includes two classes related to timingjava.util.Timer and java.util.TimerTask. These are both pretty much the same as what you might be used to with J2SE.

Table 5.3. java.util.Timer

Method

Description

Timer()

Constructs a new Timer object.

void cancel()

Stops a Timer.

void schedule(TimerTask task, Date d)

Schedules a task to run at the specified time d.

void schedule(TimerTask task, Date firstTime, long period)

Schedules a task to run first on the specified date, and then every period milliseconds.

void schedule(TimerTask task, long delay)

Schedules a task to run once after a certain delay in milliseconds has passed.

void schedule(TimerTask task, long delay, long period)

Schedules a task to run after a certain delay in milliseconds has passed, and then every period milliseconds.

void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)

Schedules a task to run continuously from firstTime onward, and then continuously using a fixed interval of period milliseconds.

void scheduleAtFixedRate(TimerTask task, long delay, long period)

Schedules a task to run continuously after delay milliseconds, and then continuously using a fixed interval of period milliseconds.


Table 5.4. java.util.TimerTask

Method

Description

TimerTask()

Constructs a new timer task.

boolean cancel()

Terminates the task.

abstract void run()

This method is overridden with a method containing the code to be executed when the Timer event goes off.

long scheduledExecutionTime()

Returns the exact time at which the task was run last.


Timers are useful when you want to execute something at regular intervals, such as when you want to clear unused resources periodically or trigger events within your game. Take a look at a Timer in action.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;

/**


 * A MIDlet which demonstrates a Timer in action.
 * @author Martin J. Wells
 */
public class TimerTest extends javax.microedition.midlet.MIDlet
{
   private Form form;
   private Timer timer;
   private PrintTask task;

   /**
    * MIDlet constructor that creates a form, timer and simple task. See the
    * inner class PrintTask for more information on the task we'll be executing.
    */
   public TimerTest()
   {
      form = new Form("Timer Test");

      // Setup the timer and the print timertask
      timer = new Timer();
      task = new PrintTask();
   }

   /** 
    * Called by the Application Manager when the MIDlet is starting or resuming
    * after being paused. In this example it acquires the current Display object
    * and uses it to set the Form object created in the MIDlet constructor as
    * the active Screen to display.
    * @throws MIDletStateChangeException
    */
   protected void startApp() throws MIDletStateChangeException
   {
      // display our UI
      Display.getDisplay(this).setCurrent(form);
 
      // schedule the task for execution every 100 milliseconds
      timer.schedule(task, 1000, 1000);
   }
   
   /**
    * Called by the MID's Application Manager to pause the MIDlet. A good
    * example of this is when the user receives an incoming phone call whilst
    * playing your game. When they're done the Application Manager will call
    * startApp to resume. Use this in order to stop the timer from running.
    */
   protected void pauseApp()
   {
      task.cancel();
   }
   
   /**
    * Called by the MID's Application Manager when the MIDlet is about to
    * be destroyed (removed from memory). You should take this as an opportunity
    * to clear up any resources and save the game. For this example we cancel
    * the timer.
    * @param unconditional if false you have the option of throwing a
    * MIDletStateChangeException to abort the destruction process.
    * @throws MIDletStateChangeException
    */
   protected void destroyApp(boolean unconditional)
            throws MIDletStateChangeException
   {
      timer.cancel();
   } 
   /**
    * An example of a TimerTask that adds some text to the form.
    */
   class PrintTask extends TimerTask
   {
      /**
       * To implement a task you need to override the run method.
       */
      public void run()
      {
         // output the time the task ran at
         form.append("" + scheduledExecutionTime());
      }
   }
}

The TimerTask is the big boss in all of this. Think of it like a manager two days after installing Microsoft Projectit controls execution of all of its associated TimerTasks with mind-numbing precision.

The API to achieve all of this is relatively simple. As you can see in the sample code just shown, a new Timer object and TimerTask are instantiated in the constructor with the following code:

timer = new Timer();
task = new PrintTask();

Notice from the second line that you're not constructing a TimerTask, but a PrintTask. If you look down in the code, you'll see a declaration for the PrintTask inner class, which extends the TimerTask abstract base class. The PrintTask then implements the required abstract run method; it's this run method that appends the text lines to the display.

The constructor schedules execution of the printTask using:

timer.schedule(task, 1000, 1000);

You can use a variety of schedule methods to determine when your tasks should run, including running once from a certain time or continuing to run at regular intervals after that time. You can also execute tasks after a certain delay (in milliseconds), optionally continuing at regular intervals.

There are two special scheduleAtFixedRate methods that ensure a task is run an absolute number of times. Use these methods if you always want a task to run the appropriate number of times, even if the application is busy doing something else immediately after the interval time has passed. This is different than regular scheduling, which will execute a task only once even if the allotted interval has passed multiple times; the Timer will run a scheduleAtFixedRate once for every interval that has passed.

Stopping tasks is also pretty easy. You can see an example of this in the pauseApp method.

task.cancel();

This call will stop all further execution of the task. Note that this is a call to the PrintTask object's cancel method, not to the Timer object. A call to the more general-purpose timer.cancel will result in the timer itself stopping, along with every task scheduled for execution.

    Table of ContentsThe MIDlet ApplicationNetworking