标签:
定时器是一种特殊的多线程,使用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 }
小练习:
间隔一分钟扫描某个目录下是否存在指定文件
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 }
标签:
原文地址:http://www.cnblogs.com/sherrykid/p/4592363.html