定时器是一种特殊的多线程,使用Timer来安排一次或者重复执行某个任务
package org.zln.thread; import java.util.Date;
import java.util.Timer;
import java.util.TimerTask; /**
* Created by coolkid on 2015/6/21 0021.
*/
public class TestTimerTask extends TimerTask {
@Override
public void run() {
System.out.println(new Date());
} public static void main(String[] args) {
Timer timer = new Timer();
TestTimerTask testTimerTask = new TestTimerTask();
timer.schedule(testTimerTask,1000,1000); }
}
E:\GitHub\tools\JavaEEDevelop\Lesson1_JavaSe_Demo1\src\org\zln\thread\TestTimerTask.java
Timer是一个定时容器,TimerTask子类是具体任务实现类
小练习:
间隔一分钟扫描某个目录下是否存在指定文件
package org.zln.thread; import java.io.File;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask; /**
* Created by coolkid on 2015/6/21 0021.
*/
public class TestTimerTask extends TimerTask { private String path;
private boolean flag = true; public TestTimerTask(String path) {
this.path = path;
} @Override
public void run() {
File file = new File(path);
if (flag&&!file.isDirectory()&&file.exists()){
System.out.println(new Date()+"已检测到文件");
flag = false;
}
if (!flag){
System.out.println(new Date()+"已经检测到文件,无需再次检测");
}
if (flag&&(file.isDirectory()||!file.exists())){
System.out.println(new Date()+"未检测到文件");
}
} public static void main(String[] args) {
Timer timer = new Timer();
TestTimerTask testTimerTask = new TestTimerTask("E:\\GitHub\\tools\\实用jar程序\\创建或删除标识文件\\zln.txt");
timer.schedule(testTimerTask,1000,60000); }
}
E:\GitHub\tools\JavaEEDevelop\Lesson1_JavaSe_Demo1\src\org\zln\thread\TestTimerTask.java
其他常用Timer方法
Modifier and Type | Method and Description |
---|---|
void |
cancel()
Terminates this timer, discarding any currently scheduled tasks.
|
int |
purge()
Removes all cancelled tasks from this timer's task queue.
|
void |
schedule(TimerTask task, Date time)
Schedules the specified task for execution at the specified time.
|
void |
schedule(TimerTask task, Date firstTime, long period)
Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.
|
void |
schedule(TimerTask task, long delay)
Schedules the specified task for execution after the specified delay.
|
void |
schedule(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
|
void |
scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
|
void |
scheduleAtFixedRate(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
|