J2ME Timer Usage Guide

Source: Internet
Author: User
Tags exit execution generator thread
A new improvement in J2SE 1.3 is to provide a simpler timer class for multitasking execution, which is done by a background thread. MIDP also includes this improvement, which benefits the J2ME developers.

J2ME prompts two classes to define and debug tasks, respectively, TimerTask and Timer. TimerTask is a user-defined abstract base class for all tasks that need to be scheduled. The Timer class is responsible for creating and managing the execution thread when the task executes.

To define a task, define a timertask subclass and implement the Run method. For example

Import java.util.*;

public class MyTask extends TimerTask
{
public void Run ()
{
System.out.println ("Running the Task");
}
}



Do you think the Run method is familiar? That's because TimerTask implements the Java.lang.Runnable interface. The Timer class calls this run method to perform individual tasks. It is also important to note that the tasks performed by each run method must be terminated as quickly as possible, because each Timer object can perform only one task at a time.

Once you define a task, you can generate a Timer object and call the schedule method to schedule it, as shown in the following code:

Import java.util.*;

Timer timer = new timer ();
TimerTask task = new MyTask ();

Wait 10 seconds before performing this task ...
Timer.schedule (task, 10000);

Wait 10 seconds before performing a task, and then do it again every 10 seconds
Timer.schedule (Task, 5000, 10000);



The schedule method is overloaded four times, and each task can be executed at a specific point in time (specified with a Date object) or after a specific time period (in milliseconds). You can schedule this task to be performed only once or repeatedly over a specific period of time. The Timer also provides a Scheduleatfixedrate method to specify the period of time that is extended repeatedly when the task is executed for the first time. If a task is delayed, the task that is scheduled to be performed in the back is shortened by the waiting time to "connect" the delayed task.

Each Timer object creates and manages a background thread. In general, a program to create a Timer is enough, of course, you can create as many as necessary. You can also stop a Timer at any time and terminate the background thread by calling the Cancel method. Note, however, that once the timer is terminated, it is impossible to resume execution unless you regenerate a timer object and rearrange the tasks you want to perform. The timer object is thread-safe, and you can access the timer object directly in a multi-threaded environment without any explicit synchronization.

In addition, each task provides a Cancel method (inherited from the TimerTask base class) that you can call to terminate the task during the execution of the task. Once you terminate the task, it will exit the Task Scheduler. You can call the Cancel method of each task at any time to terminate execution of the task, even if the task has not been executed once.

Here's a simple MIDlet example to illustrate the use of timers, which we'll use to simulate the effect of a star moving. The stars are represented by a point, which uses the low-boundary graphics API. For a more detailed description of the low-boundary graphics API, please refer to my other article, "Using MIDP's low-bound user interface API."

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

public class Timerdemo extends MIDlet {

Display display;
Starfield field = new Starfield ();
Fieldmover mover = new Fieldmover ();
Timer timer = new timer ();

Public Timerdemo () {
display = Display.getdisplay (this);
}

protected void Destroyapp (Boolean unconditional) {
}

protected void startApp () {
Display.setcurrent (field);
Timer.schedule (Mover, 100, 100);
}

protected void Pauseapp () {
}

public void exit () {
Timer.cancel (); Stop scrolling
Destroyapp (TRUE);
Notifydestroyed ();
}

Class Fieldmover extends TimerTask {
public void Run () {
Field.scroll ();
}
}

Class Starfield extends Canvas {
int height;
int width;
Int[] stars;
Random generator = new Random ();
Boolean painting = false;

Public Starfield () {
Height = getheight ();
width = getwidth ();
Stars = new int[height];

for (int i = 0; i < height; ++i) {
Stars[i] =-1;
}
}

public void Scroll () {
if (painting) return;

for (int i = height-1 i > 0; i.) {
Stars[i] = stars[i-1];
}

Stars[0] = (generator.nextint ()%
(3 * width)) /2;
if (Stars[0] >= width) {
Stars[0] =-1;
}

Repaint ();
}

protected void Paint (Graphics g) {
painting = true;

G.setcolor (0, 0, 0);
G.fillrect (0, 0, width, height);

G.setcolor (255, 255, 255);

for (int y = 0; y < height; ++y) {
int x = Stars[y];
if (x = = 1) continue;

G.drawline (x, y, x, y);
}

painting = false;
}

protected void keypressed (int keycode) {
Exit ();
}
}
}



Timerdemo MIDlet used a Timer object timer to dispatch a TimerTask task Fieldmover, with a time gap of 100 milliseconds. Fieldmover processing the star's update and redraw the task, so that the entire sky continues to the bottom of the screen "extension." This creates a simple star-moving effect.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.