Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。
TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。
应用场景:在指定的时间之后执行某操作
public class TimerTestActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Timer timer = new Timer();
timer.schedule(timerTask, 3000);// 在3秒后执行子线程timerTask
}
TimerTask timerTask = new TimerTask()
{
@Override
public void run()
{
Message message = new Message();
message.what = 1;
handler.sendMessage(message);// 发送消息
}
};
Handler handler = new Handler()
{
public void handleMessage(Message msg)// 处理消息
{
switch (msg.what)
{
case 1:
setTitle("Hello,I am Harvey");
Toast.makeText(TimerTestActivity.this, "Hello,I am Harvey", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
};
}
2
import java.util.Timer;
import java.util.TimerTask;
/**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new Reminder(5);
System.out.println("Task scheduled.");
}
}