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.