Java timer that limits the amount of time a method can run for

Viewed 155

I am writing a web crawler and part of the specifications is that it will crawl the web for a user-specified amount of time. In order to do that I am trying to use the Timer and TimerTask methods. The code I have now is attempt number two. I have watched a few tutorials though none of them are quite what I need. I have also read through the documentation. I have been working on this project for a few weeks now and it is due tonight. I am not sure where to turn to next.

    public void myTimer (String url, long time)
 {
    Timer webTimer = new Timer();
    TimerTask timer;
    timer = new TimerTask()
    {


        public void run()
        {
            long limit = calculateTimer(time);
            while(System.currentTimeMillis() < limit)
            {
                webcrawler crawler1 = new webcrawler();
                crawler1.Crawl(url);
            }
        System.out.println("times Up");
        }
    };
    webTimer.schedule(timer, 1000);

}
1 Answers

I am guessing the .Crawl() is starting a loop and keeping that thread busy, which means it cannot check the while condition. I do not know your implementation of the crawler but i would recommend a function stopCrawling which would set a boolean to true to break the loop inside that class. Than I would do something like this:

public void startCrawler (String url, long time){

    webcrawler crawler1 = new webcrawler();
    crawler1.Crawl(url);

    TimerTask task = new TimerTask() {
        public void run() {
            crawler1.stopCrawling()
        }
    };
    Timer timer = new Timer("Timer");

    timer.schedule(task, time);


}
Related