1、指定延迟时间+循环执行操作
public class TimerTest {
String path = "C:\\Users\\Administrator\\Desktop\\";
Timer timer;
public TimerTest(int time){
timer = new Timer();
timer.schedule(new timeTaskTest() , time*1000, 2000);//timer.schedule(执行的方法,延迟多久执行(ms))
}
class timeTaskTest extends TimerTask{
@Override
public void run() {
File dir = new File(path);
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (!file.isDirectory()) {
String fileName = file.getName();
if (fileName.equals("false.txt")) {
System.out.println("文件名:" + fileName + ",还存在!!!");
}else if (fileName.equals("true.txt")) {
System.out.println("文件false.txt被修改!!!");
timer.cancel();
System.out.println("取消定时任务!!!");
}
}
}
}
}
}
public static void main(String[] args) {
System.out.println("timer begin...");
new TimerTest(3);
}
}
2、指定时间执行操作
public class TimerTest1 {
Timer timer;
public TimerTest1() {
Date date = getTime();
System.out.println("指定时间:" + date);
timer = new Timer();
timer.schedule(new TimerTaskTest2(), date);// timer.schedule(执行的方法,要执行的时间)
}
public Date getTime() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 11);
calendar.set(Calendar.MINUTE, 33);
calendar.set(Calendar.SECOND, 00);
Date date = calendar.getTime();
return date;
}
class TimerTaskTest2 extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("指定时间执行线程任务...");
}
}
public static void main(String[] args) {
new TimerTest1();
}
}