Another facility offered by Java's concurrency framework is to schedule a thread after certain time or at regular interval (like standard unix cron job). There are 2 ways to schedule the thread at regular interval. First one is to run a task at regular interval regardless of the previous job. Second one is to run a task and wait for the certain interval after the previous job is done.
Second one is helpful in situation like crawlers. It is necessary to download the pages with some politeness factor [wait for sometime before downloading a page from the same website].
ScheduledExecutorService executionService = Executors.newScheduledThreadPool(2);
Above code snippet create a pool of 2 threads. This service can schedule the threads at regular interval.
ScheduledExecutorService provide a method schedule
Runnable task = new Runnable() {
public void run() {
System.out.println( "I am responsible for downloading a page" );
return;
}
};
/* TimeUnit is defined within java.util.concurrent package */
Future future = executionService.schedule(task, 2000, TimeUnit.MILLISECONDS);
The above code schedule a task to run after 2 seconds [2000 milliseconds]. schedule method return a future object. This future object can be used to check the status of the task [isDone method] or to cancel the task [cancel method]. Read more about the future object and the methods available here.
ScheduledExecutorService also support repeated execution of a task via scheduleAtFixedRate and scheduleWithFixedDelay.
scheduleAtFixedRate method schedule the task at regular interval. This method does not check if the previously scheduled task is finshed or not.
scheduleWithFixedDelay method is similar to scheduleAtFixedRate except that this method wait for the previous execution to finish, wait for the fixed interval and then schedule the task again.
No comments:
Post a Comment