2016-10-13 28 views
-1

下面是一个测试Timertask类,我一直在试验。基本上,timertask在一个文件改变时观察,然后执行一些方法。我希望打印给用户的消息,例如,只要timertask正在运行,就等待“等待文件更改发生”。命令应该输入哪里?以下是我的代码。Java - 只要TimerTask正在运行,打印消息

谢谢!

public class FileWatcherTest { 

static int count = 3; 
static int i = 0; 

public static void main(String[] args) { 

    final Timer timer = new Timer(); 
    System.out.println("Starting Timer " + timer.toString()); 

    TimerTask task = new FileWatcher(new File("c:/temp/text.txt")) { 

     protected void onChange(File file) {    
      i++; 
      System.out.println("Executing iteration " + i); 
      System.out.println("File " + file.getName() + 
        " have change !"); 
      // code to cancel timer 
      if (i >= count) { 
       System.out.println("Finished Iterations"); 
       System.out.println("Stopping Timer"); 
       timer.cancel(); 
       System.out.println("Stopped Timer"); 

      } else { 

      } 
     } 
    }; 

     // repeat the check every second 
    timer.schedule(task, new Date(), 1000); 
} 
    } 
+0

什么是'TimerTask任务=新的FileWatcher'应该是什么意思? – njzk2

+0

它是一个扩展TimerTask的抽象类。基本上监视修改日期的文件。 – spry

+0

你什么时候打电话给'onChange'? – njzk2

回答

0

我假设你FileWatcher扩展TimerTask的,这意味着它实现的run()。你可以把代码放到你的run方法中,如果它没有调用onChange()就会打印一条消息。

+0

我建议在run方法中添加一个打印命令。它可以工作,但是在定时器停止后它还会再打印一次。 – spry

+0

发现错误。打印是在一个循环之后。将其更改为循环之前,它现在可以工作。 – spry

0

打印是在一个循环之后。将其更改为循环之前,它现在可以工作。