java timer定時器簡單實用
阿新 • • 發佈:2018-12-19
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(); } }