定时器是一种特殊的多线程,使用Timer来安排一次或者重复执行某个任务
1 package org.zln.thread; 2 3 import java.util.Date; 4 import java.util.Timer; 5 import java.util.TimerTask; 6 7 /** 8 * Created by coolkid on 2015/6/21 0021. 9 */ 10 public class TestTimerTask extends TimerTask { 11 @Override 12 public void run() { 13 System.out.println(new Date()); 14 } 15 16 public static void main(String[] args) { 17 Timer timer = new Timer(); 18 TestTimerTask testTimerTask = new TestTimerTask(); 19 timer.schedule(testTimerTask,1000,1000); 20 21 } 22 }
Timer是一个定时容器,TimerTask子类是具体任务实现类
小练习:
间隔一分钟扫描某个目录下是否存在指定文件
1 package org.zln.thread; 2 3 import java.io.File; 4 import java.util.Date; 5 import java.util.Timer; 6 import java.util.TimerTask; 7 8 /** 9 * Created by coolkid on 2015/6/21 0021. 10 */ 11 public class TestTimerTask extends TimerTask { 12 13 private String path; 14 private boolean flag = true; 15 16 public TestTimerTask(String path) { 17 this.path = path; 18 } 19 20 @Override 21 public void run() { 22 File file = new File(path); 23 if (flag&&!file.isDirectory()&&file.exists()){ 24 System.out.println(new Date()+"已检测到文件"); 25 flag = false; 26 } 27 if (!flag){ 28 System.out.println(new Date()+"已经检测到文件,无需再次检测"); 29 } 30 if (flag&&(file.isDirectory()||!file.exists())){ 31 System.out.println(new Date()+"未检测到文件"); 32 } 33 } 34 35 public static void main(String[] args) { 36 Timer timer = new Timer(); 37 TestTimerTask testTimerTask = new TestTimerTask("E:\\GitHub\\tools\\实用jar程序\\创建或删除标识文件\\zln.txt"); 38 timer.schedule(testTimerTask,1000,60000); 39 40 } 41 }
其他常用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.
|