Timer类可以将程序的某一执行任务放在后台线程中,可以是只执行一次或者在指定间隔内重复执行该任务
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TimerMidlet extends MIDlet implements CommandListener
{
private Display display;
private Form form;
private Command exit;
private Command stop;
private Timer timer;
private RunTimerTask tt;
private int count = 0;
public timerMidlet()
{
form = new Form("Timer");
exit = new Command("Exit", Command.EXIT, 1);
stop= new Command("Stop", Command.STOP, 2);
}
public void startApp ()
{
display = Display.getDisplay(this);
form.addCommand(exit);
form.addCommand(stop);
form.setCommandListener(this);
//每3秒重复一次
timer = new Timer();
tt = new RunTimerTask();
timer.schedule(tt,0, 3000);
display.setCurrent(form);
}
public void destroyApp (boolean unconditional){}
public void pauseApp () { }
public void commandAction(Command c, Displayable d)
{
if (c == stop)
{
timer.cancel();
}
else if (c == exit)
{
destroyApp(false);
notifyDestroyed();
}
}
/*--------------------------------------------------
* RunTimerTask 类 - 运行任务
*-------------------------------------------------*/
private class RunTimerTask extends TimerTask
{
public final void run()
{
form.append("计数: " + ++count + "/n");
}
}
}
本文介绍了一个使用Java实现的定时任务示例,通过Timer类在指定时间间隔内重复执行任务。展示了如何创建定时器、调度任务及停止定时器的方法。
1105

被折叠的 条评论
为什么被折叠?



