- public class Test {
- public static void main(String[] args) {
- Timer timer = new Timer();
- timer.schedule(new MyTask(), 1000, 3000); //定时器1秒后开始,每隔3s执行一次
- }
- }
- class MyTask extends TimerTask {
- @Override
- public void run() {
- System.out.println("执行");
- }
- }
android 中除了可以用定时器来执行定时任务,也可以通过Handler来执行任务
private void update(){
new Thread(){
public void run() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
Message message = handler.obtainMessage();
message.what = 1;
handler.sendMessage(message);
}
}, 1000);
};
}.start();
}
new Thread(){
public void run() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
Message message = handler.obtainMessage();
message.what = 1;
handler.sendMessage(message);
}
}, 1000);
};
}.start();
}
通过发送消息给handleMessage
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
update();
break;
default:
break;
}
};
};
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
update();
break;
default:
break;
}
};
};