定时器Timer、TimerTask时间任务类
package com.tender.news.crawler;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerThread {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask tt1 = new MyTask(1);
timer.schedule(tt1, 200);// 2秒后执行任务1
TimerTask tt2 = new MyTask(2);
timer.schedule(tt2, 500, 1000);// 3秒后执行任务2并每隔1秒执行一次
TimerTask tt3 = new MyTask(3);
Date date = new Date(System.currentTimeMillis() + 1000);
timer.schedule(tt3, date);// 指定时间1秒后执行任务
try {
Thread.sleep(15000);// 15秒后取消任务
} catch (Exception e) {
System.out.println("出现错误:" + e.getMessage());
}
timer.cancel();
System.out.println("任务定时器已经被取消");
}
}
//
class MyTask extends TimerTask {
private int taskID = 1;
public MyTask(int id) {
this.taskID = id;
}
@Override
public void run() {
System.out.println("开始执行我的第" + this.taskID + "个任务,执行时间为:"
+ new Date().toLocaleString());
}
}