0
public ProcessPage(String url, String word){

    getDocument(url);
    Elements links = doc.getElementsContainingText(word);

    print("\nRetrieved Links: ");
    for (Element link : links) {

        if (link.attr("abs:href") != "") {
            print(" * ---- <%s>  (%s)", link.attr("abs:href"),
                    trim(link.text(), 35));
        }
    }
}

I want this method to run every (let's say 10) minutes... what should I do?

wassgren
  • 18,651
  • 6
  • 63
  • 77
Bardia Sh
  • 3
  • 1

2 Answers2

2

You can use a ScheduledExecutorService to schedule a Runnable or a Callable. The scheduler can schedule tasks with e.g. fixed delays as in the example below:

// Create a scheduler (1 thread in this example)
final ScheduledExecutorService scheduledExecutorService = 
        Executors.newSingleThreadScheduledExecutor();

// Setup the parameters for your method
final String url = ...;
final String word = ...;

// Schedule the whole thing. Provide a Runnable and an interval
scheduledExecutorService.scheduleAtFixedRate(
        new Runnable() {
            @Override
            public void run() {

                // Invoke your method
                PublicPage(url, word);
            }
        }, 
        0,   // How long before the first invocation
        10,  // How long between invocations
        TimeUnit.MINUTES); // Time unit

The JavaDocs describes the function scheduleAtFixedRate like this:

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.

You can find out more about the ScheduledExecutorService in the JavaDocs.

But, if you really want to keep the whole thing single-threaded you need to put your thread to sleep along the lines of:

while (true) {
    // Invoke your method
    ProcessPage(url, word);

    // Sleep (if you want to stay in the same thread)
    try {
        Thread.sleep(1000*60*10);
    } catch (InterruptedException e) {
        // Handle exception somehow
        throw new IllegalStateException("Interrupted", e);
    }
}

I would not recommend the latter approach since it blocks your thread but if you only have one thread....

IMO, the first option with the scheduler is the way to go.

wassgren
  • 18,651
  • 6
  • 63
  • 77
0

Would that suit you ?

Timer timer = new Timer();
timer.schedule((new TimerTask() {
    public void run() {
        ProcessPage(url, word);
    }                   
}), 0, 600000); //10 minutes = 600.000ms

See the javadoc here : http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#schedule(java.util.TimerTask,%20long,%20long)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

Frazew
  • 1
  • 2