-1

Below is a test Timertask class that i have been experimenting with. Basically the timertask watches when a file changes and then executes some methods. I want a message printed to the user, eg."Waiting for file change to occur" as long as the timertask is running . Where should the command be input?. Below is my code.

Thanks!

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);
}
    }
spry
  • 3
  • 2

2 Answers2

0

I'm assuming your FileWatcher extends TimerTask, which means it implements run(). You could put code inside your run method that would print a message if it doesn't call onChange().

billoot
  • 77
  • 15
  • I added a print command in the run method as suggested. It works, but it also prints one more time after the timer has stopped. – spry Oct 13 '16 at 21:36
  • Found the mistake. The print was after a loop. Changed it to before the loop and it works now. – spry Oct 13 '16 at 21:56
0

The print was after a loop. Changed it to before the loop and it works now.

spry
  • 3
  • 2